简体   繁体   中英

jdbc connection with java, singleton connection object or spring jdbc connection?

I am manipulating a postgresql database with java. Please help me to choose a development practice.

Must I:

  • create a jdbc singleton object?
  • create a new connection for every request?
  • or use the jdbc api for spring framework?

Which is the best practice?

A vague answer for a vague question:

Rather have your JDBC connections managed. If you have too many connections open, you will have to maintain them and make sure they're closed for other connections to access the database (you can have an Exception stating "Too many open files"). Connection Pooling maintains your connection. Have 1 connection per request and once you're done, return it back to the pool.

I would do this:

  • Have my JDBC connections maintained in a Connection Pool (thanks Jigar Joshi ).
  • Request the connection from the Connection Pool and use it in my DAO (the DAO is what does the CRUD of my object to DB).
  • Once connection is done, return the connection to the Connection Pool.

If you're using Spring, use the Spring JDBC Template .

Where can I find good instructions or a tutorial on how to do connection pooling for JDBC to a Postgres database on my client?

http://www.mchange.com/projects/c3p0/index.html

c3p0 was designed to be butt-simple to use. Just put the jar file [lib/c3p0-0.9.0.jar] in your application's effective CLASSPATH, and make a DataSource like this:

import com.mchange.v2.c3p0.*;

...

ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver            
cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" );
cpds.setUser("dbuser");                                  
cpds.setPassword("dbpassword");    

[Optional] If you want to turn on PreparedStatement pooling, you must also set maxStatements and/or maxStatementsPerConnection (both default to 0):

cpds.setMaxStatements( 180 ); 

Do whatever you want with your DataSource, which will be backed by a Connection pool set up with default parameters. You can bind the DataSource to a JNDI name service, or use it directly, as you prefer. When you are done, you can clean up the DataSource you've created like this:

DataSources.destroy( cpds );

That's it. The rest is detail.

Maintain a single connection or even better use Connection-pooling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM