Where to close the connection while using connection pooling? - java

I am using Vaadin framework and following MVC design pattern to develop a web application project.
While implementing connection pooling feature for my project I encountered the following problem.
I am getting the ResultSet in one class(data class) and I am using that ResultSet in another class(Business Logic).
I have to close the connection object after using that ResultSet in the business logic class.
What may be the efficient way to achieve this without passing the connection object to the business logic class?
Please Explain.Thank You.

I would recommend that you write a Dao which returns a List of Business Objects and NOT the resultsets. The connection must be closed in the Dao itself. Below is an example
public class PersonDao {
private DataSource ds; //add a setter and inject the JDBC resource
public List<Person> getPersons() {
List<Person> personList = new ArrayList();
Connection con;
PreparedStatement pstmt;
try {
con = ds.getConnection(username, password);
pstmt = con.prepareStatement("SELECT * FROM PERSON");
ResultSet rs = pstmt.executeQuery(query);
//Fetch the resultset, iterate over it and populate the list
while (rs.next()) {
Person p = new Person();
p.setName(rs.getString("name");
personList.add(p);
}
} catch (Exception ex {
// ... code to handle exceptions
} finally {
if (con != null) con.close();
}
return personList;
}
If you can use Java 7, you can also use try with resource which would automatically handle the closing of connections for you. If you are not in a position to change the Dao interface, then it is a good idea to write a layer between the Dao and the business layer.

Related

Connector class from JDBC

I'm learning about JDBC and I have learned the steps: open connection, execute statement, get result, etc. I know about Connection, Statements and the other interfaces, but I just found a tutorial with another class, the Connector class. And I don't understand what exactly we can do with this Connector class. I have made some app without this class and I don't understand why do I need the Connector class? Any feedback will be apreciated!
Here is the code:
public Set getAllUsers() {
Connector connector = new Connector();
Connection connection = connector.getConnection();
try {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM user");
Set users = new HashSet();
while(rs.next())
{
User user = extractUserFromResultSet(rs);
users.add(user);
}
return users;
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}
UPDATE:
This is the link where you can find the entire code: https://dzone.com/articles/building-simple-data-access-layer-using-jdbc
Your Connector is probably a class with a factory method:
the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.
Basically it is a utility class to create a Connection hiding the complexity of connection creation.

JDBC helper that reduces boilerplate code

I am using the c3p0 library as my datasource object.
I want to create a JDBC helper class that helps reduce the boilerplate code that JDBC has and I am wondering if my implementation is correct and are following best practices? Also, if there is an already existing library that provides these functionalities, like QueryRunner, maybe?
Most of my queries returns a list of results of a specified column. Will it be okay if I use the following helper method for all my queries?
public List<String> retrieveSQLQuery(String sqlQuery, String column) {
List<String> values = new ArrayList<>();
try (Connection conn = getConnection();
PreparedStatement statement = conn.prepareStatement(sqlQuery);
ResultSet rs = statement.executeQuery(sqlQuery)) {
while (rs.next()) {
values.add(rs.getString(column));
}
} catch (SQLException e) {
e.printStackTrace();
}
return values;
}
The getConnection() method lives in a JDBCUtil class which provides the connection to the datasource object. This helper class will be extending JDBCUtil thus why it has access to that method.
I also know that frameworks like spring and Hibernate provide utilities, however, those frameworks are too large for my project.

Can my connection object made available on all my forms? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm developing a java based application using NetBeans. My app opens with a window with asks the user to enter their credentials and based on data entered, a connection is established between the app and my MySQL client (I'm using JDBC for this purpose).
My issue: I want the connection object (which is declared and initialized after checking the credentials of the user) to be available for use in all my form. Previously, i have being doing this by passing the connection object from one form to another. But i don't want to do that! I want once this connection object is declared, it's made available to all the forms in the app.
I want the connection object (...) to be available for use in all my form
You should not have an open connection while your application lives. Instead, use a database connection pool of 1 or 2 connections that will be available for all the application and add a shutdown hook to close this data source when the application finishes. The connection pool will take care to maintain the connections alive and use low resources for it.
For example: your user opens the application and enters its credentials, then leaves the room because he/she has to do some paperwork and takes 30 mins, then goes back to the pc and try to use an option. If using a static Connection con object, you manually opened a physical connection to the database and you're in charge to control the connectivity for all these 30 minutes, and if you don't do any action in that time then probably the physical connection was closed by the database engine. If using a connection pool, this will take care of opening/closing physical connections and maintaining them in sleep state so your connection won't be lost.
Note that your Connection object and related resources (PreparedStatement, ResultSet, etc). should be in the narrowest possible scope.
Here's a minimal example of doing this using BoneCP as database connection pool.
public class ConnectionProvider {
private static DataSource dataSource;
private static boolean initialized = false;
public static void init(Map<String, String> conf) {
if (!initialized) {
//synchronization to avoid multiple threads accesing to this part of the method
//at the "same time"
synchronized(DataSourceProvider.class) {
//double validation in case of multi threaded applications
if (!initialized) {
//you may add more validations here
//in case you want to use another datasource provider
//like C3PO, just change this part of the code
BoneCPDataSource bds = new BoneCPDataSource();
bds.setDriverClass(conf.get("driver"));
bds.setJdbcUrl(conf.get("url"));
bds.setUsername(conf.get("user"));
bds.setPassword(conf.get("password"));
//this should be obtained as configuration parameter
bds.setMaxConnectionsPerPartition(2);
//you can add more BoneCP specific database configurations
dataSource = bds;
initialized = true;
}
}
}
}
public static Connection getConnection() {
if (dataSource == null) {
//this should be a custom exception in your app
throw new RuntimeException("Data Source was not initialized.");
}
return dataSource.getConnection();
}
}
And the client (once you have called the init method and provided the database configurations). I'm avoiding exception handling for brevity:
public class SomeDao {
private Connection con;
//using Dependency Injection by composition for DAO classes with connection
public SomeDao(Connection con) {
this.con = con;
}
public SomeEntity getSomeEntity(int id) {
String sql = "SELECT id, col1, col2 FROM someEntity WHERE id = ?";
//PreparedStatement and ResultSet go on the narrowest possible scope
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
SomeEntity someEntity = new SomeEntity();
if (rs.hasNext()) {
someEntity.setId(rs.getInt("id");
//similar for other columns...
}
//don't forget to close the resources after its usage
return someEntity;
}
}
public class SomeService {
public SomeEntity getSomeEntity(int id) {
//retrieving the connection at this level
//a service may access to several daos
Connection con = ConnectionProvider.getConnection();
//performing the operations against DAO layer
SomeDao someDao = new SomeDao(con);
SomeEntity someEntity = someDao.getSomeEntity(id);
//closing the connection. This is A MUST
//here the connection pool won't close the physical connection
//instead put it to sleep
con.close();
//return the proper data at a single point of the method
return someEntity;
}
}
Don't use the same Connection in your application! But what you want to achieve could be done using static variable. For example, add the following code to any of your classes, or create a new class for it:
private static Connection con = null;
public static Connection getConnection (String url)
{
if (con == null)
con = DriverManager.getConnection(url);
return con;
}
Then, call MyClass.getConnection("jdbc:mysql://localhost:3306/") or whatever the connection string is, and it will return one Connection that you could use for all classes.

Correct way to return resultset of a query in java

I want to know what is the correct way to return resultset in form of some Collection.
Or should I create class instances of same class and then return it (how to do that ?)
What is the common practice to do this? Or should I learn Hibernate and implement that?
public class Author {
private String table_name = "authors";
int id;
String full_name;
String location;
int age;
String details;
/** Getter Setter Methods here ....*/
/** Constructor here.... */
/* Returns all Authors */
public ArrayList all() {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
/* TODO : figure out which collection is suitable .*/
DbHelper dbHelper = new DbHelper();
Connection conn = dbHelper.getConnection();
ResultSet rs = null;
Statement stmt = null;
try {
stmt = conn.createStatement();
String query = "SELECT * FROM authors";
rs = stmt.executeQuery(query);
while (rs.next()) {
HashMap<String, String> hashmap = new HashMap<>();
int id = rs.getInt(1);
hashmap.put("id",rs.getString(1));
hashmap.put("full_name", rs.getString(2));
hashmap.put("location", rs.getString(3));
hashmap.put("age", rs.getString(4));
hashmap.put("details", rs.getString(5));
list.add(id,hashmap);
//hashmap.clear();
}
} catch (SQLException ex) {
Logger.getLogger(Author.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("you are fuckt");
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(Author.class.getName()).log(Level.SEVERE, null, ex);
}
}
return list;
}
}
I would say you should go for hibernate. you will get the list of objects just by performing "list()" method.
code for your reference
List<Authors> al = this.sessionFactory.getCurrentSession().createQuery("from Authors").list();
Hibernare provides many other advantages too. Its definitely better option than JDBC.
JDBC alternative:
best practices says that u should return a DTO(Data transfer object) from DAO layer because it is advisable to get the relevant data in one go from DB so u can minimize the DB hits. Follow This:
List<YourDTO> al = new ArrayList<yourDTO>();
YourDTO is:
class YourDTO
{
private int id:
private Authors authors;
// getters and setters
}
read the data from resultSet as your doing then create the objects of Authors , set the fields , add them to ArrayList with id.
There are many good options available:
Spring JDBC is a very good choice for mostly read db apps.
Jooq is a one of the most advanced java querying alternatives, but it's free of charge only for open-source dbs.
MyBatis and QueryDSL have great sql querying features, but don't match Hibernate in the create/update/delete part.
Hibernate is great for domain driven models, especially for managing complex state changes, polymorphic types. It has great features like optimistic locking, dirty checks, transactional unit of works, first and second level caches, but it takes some time to master it having a steep learning curve.
Try Spring JDBC first and if that's not enough than invest your time and effort into Hibernate.

JPAContainer connection?

I'm learning JPAContainer, and I can't understand how to configure my SGBD connection...Using DAO mode I create an class that return my connection.
//ConnectionFactory DAO mode
public class ConnectionFactory {
public Connection getConnection() {
try {
return DriverManager.getConnection(
"jdbc:mysql://localhost/fj21", "root", "");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
How to create connection for to use with JPAContainer ? What better way ?
To start define your jpa persistence unit, lets say "addressbook". Then you could create a new JPAContainer using the JPAContainerFactory.
Example:
JPAContainerFactory.make(Person.class, JpaAddressbookApplication.PERSISTENCE_UNIT); // where PERSISTENCE_UNIT = "addressbook"
Going this way you don't have to deal with the EntityManager.
I highly recommend you to follow up this tutorial and have a look at the following answer on stackoverflow: https://stackoverflow.com/a/17876743

Categories