(a) C3P0
C3P0 is the recommended connection pool for hibernate, which automatically cleans up connection, Statement, ResultSet, and requires c3p0-dependent jar packages.
Configuration file
driverclass=com.mysql.jdbc.DriverJdbcUrl=jdbc:mysql://127.0.0.1:3306/mydbuser= =w5566maxpoolsize=40minpoolsize=2initialpoolsize=10maxstatements=180
Java implementation
PublicConnection C3p0conn () {//Load configuration fileProperties props =NewProperties (); String filename= "/com/awinson/cfg/c3p0.properties"; InputStream is= This. GetClass (). getResourceAsStream (filename); Try{props.load (IS); //Create a connection pool instanceCombopooleddatasource Dsource =NewCombopooleddatasource (); //Configure the data sourceDsource.setdriverclass (Props.getproperty ("Driverclass")); Dsource.setjdbcurl (Props.getproperty ("Jdbcurl")); Dsource.setuser (Props.getproperty ("User")); Dsource.setpassword (Props.getproperty ("Password")); Dsource.setmaxpoolsize (Integer.parseint (Props.getproperty ("Maxpoolsize"))); Dsource.setminpoolsize (Integer.parseint (Props.getproperty ("Minpoolsize"))); Dsource.setinitialpoolsize (Integer.parseint (Props.getproperty ("Initialpoolsize"))); Dsource.setmaxstatements (Integer.parseint (Props.getproperty ("Maxstatements"))); //Get database connectionConnection conn =dsource.getconnection (); //Turn off transaction auto-commitConn.setautocommit (false); returnConn; } Catch(propertyvetoexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); } return NULL; }
(ii) DBCP
DBCP is an open source connection pool for the Apache foundation that relies on the two jar packages of Commons-dbcp.jar and Commons-pool.jar.
// Create a data source object New Basicdatasource (); // Configure the data source Ds.setdriver (driver); Ds.seturl (URL); Ds.setusername (username); Ds.setpassword (password); Ds.setinitialsize (initialsize); Ds.setmaxidle (maxidle); Ds.setminidle (minidle); // Get database connection Connection conn = ds.getconnection (); // releasing a database connection Conn.close ();
(iii) Supplementary
(1) The data source simply creates one, which is the factory of the database connection.
(2) It is recommended to set the data source as a static object, initialize the data source object at the beginning of the application, and direct access to the DS object where the data link is needed in the program.
The use of C3P0 and DBCP