Spring configuration DataSource Three ways database connection pool

Source: Internet
Author: User
Tags connection pooling

Respecting the original ( original link ): http://blog.csdn.net/kunkun378263/article/details/8506355

1. Using Org.springframework.jdbc.datasource.DriverManagerDataSource

Note: Drivermanagerdatasource establishes a connection as long as there is a connection to create a new connection, there is no connection pooling role.
<bean id= "DataSource" class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name= "Driverclassname" ><value>${jdbc.driverClassName}</value></property>
<property name= "url" ><value>${jdbc.url}</value></property>
<property name= "username" ><value>${jdbc.username}</value></property>
<property name= "Password" ><value>${jdbc.password}</value></property>

</bean>
2. Using Org.apache.commons.dbcp.BasicDataSource
Description: This is a recommended way to configure the data source, which really uses the connection pooling technology
<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" >
<property name= "Driverclassname" >
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name= "url" >
<value>jdbc:oracle:thin: @localhost:1521:orcl</value>
</property>
<property name= "username" >
<value>test</value>
</property>
<property name= "Password" >
<value>test</value>
</property>
<property name= "Maxactive" >
<value>255</value>
</property>
<property name= "Maxidle" >
<value>2</value>
</property>
<property name= "Maxwait" >
<value>120000</value>
</property>
</bean>
3. Using Org.springframework.jndi.JndiObjectFactoryBean
Description: Jndiobjectfactorybean is able to get datasource through Jndi
<bean id= "DataSource" class= "Org.springframework.jndi.JndiObjectFactoryBean" >
<property name= "Jndiname" ><value>java:comp/env/jdbc/roseindiadb_local</value></property >
</bean>
Summary: The first of 3 ways is not used in the connection pool, so less in the project, the third way to configure the data source in the Web server, not easy to deploy, I recommend the use of every two ways to configure the data source.

Configure a data source 
Spring contains two implementations of data sources in third-party dependency packages, one of which is Apache DBCP and the other is c3p0. You can use either of the two configuration data sources in the spring configuration file.

dbcp Data Source
The DBCP class package located in &LT;SPRING_HOME&GT;&LT;/SPRING_HOME&GT;/LIB/JAKARTA-COMMONS/COMMONS-DBCP.JAR,DBCP is a dependent Jakarta Commons-pool the pool of database connections for the object pooling mechanism, so you must also include <spring_home></spring_home>/lib/jakarta-commons/under the Classpath Commons-pool.jar. Here is a configuration fragment that uses DBCP to configure a MySQL data source:
XML code

1.<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource"
2. destroy-method= "Close" >
3. <property name= "Driverclassname" value= "Com.mysql.jdbc.Driver"/>
4. <property name= "url" value= "Jdbc:mysql://localhost:3309/sampledb"/>
5. <property name= "username" value= "root"/>
6. <property name= "password" value= "1234"/>
7.</bean>

Basicdatasource provides the close () method to turn off the data source, so you must set the destroy-method= "close" property so that the data source shuts down gracefully when the spring container is closed. In addition to the data source properties that are required above, there are some common properties:
Defaultautocommit: Sets whether the connection returned from the data source takes the auto-commit mechanism, and the default value is true;
Defaultreadonly: Sets whether the data source can only perform read-only operations, the default value is false;
Maxactive: Maximum Connection database connection number, set to 0 o'clock, indicating no limit;
Maxidle: The maximum number of waiting connections, set to 0 o'clock, indicates no limit;
Maxwait: The maximum number of seconds to wait, in milliseconds, over time will be reported error message;
Validationquery: A query SQL statement that verifies that a connection is successful, the SQL statement must return at least one row of data, as you can simply set to: "SELECT COUNT (*) from user";
Removeabandoned: Whether self-interruption, default is false;
Removeabandonedtimeout: The data connection is automatically disconnected after a few seconds, and the value is provided when removeabandoned is true;
Logabandoned: If the interrupt event is logged, the default is false;

c3p0 Data Source
C3P0 is an open source JDBC data source implementation project that is published in the Lib directory with Hibernate and implements the Connection and statement pools for JDBC3 and JDBC2 extension specification descriptions. The C3p0 class package is located in <spring_home></spring_home>/lib/c3p0/c3p0-0.9.0.4.jar. Here is an Oracle data source configured using C3P0:

XML code

1.<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource"
2. destroy-method= "Close" >
3. <property name= "Driverclass" value= "Oracle.jdbc.driver.OracleDriver"/>
4. <property name= "Jdbcurl" value= "Jdbc:oracle:thin: @localhost: 1521:ora9i"/>
5. <property name= "user" value= "admin"/>
6. <property name= "password" value= "1234"/>
7.</bean>

Combopooleddatasource and Basicdatasource provide a close () method for shutting down the data source so that we can guarantee that the data source will be released successfully when the spring container is closed.
C3P0 has richer configuration properties than DBCP, which allow for a variety of effective control over the data source:
Acquireincrement: When a connection in the connection pool is exhausted, C3P0 creates the number of new connections at once;
Acquireretryattempts: Defines the number of repeated attempts to obtain a new connection from the database after a failure, default is 30;
Acquireretrydelay: Two times the interval in the connection, in milliseconds, the default is 1000;
Autocommitonclose: All uncommitted operations are rolled back by default when the connection is closed. The default is false;
AUTOMATICTESTTABLE:C3P0 will build an empty table named Test and test it with its own query statement. If this parameter is defined, then the property preferredtestquery is ignored. You cannot take any action on this test table, it will be used in the C3P0 test, default is null;
Breakafteracquirefailure: Getting a connection failure will cause all threads waiting to get the connection to throw an exception. However, the data source is still valid and continues to try to get the connection the next time you call Getconnection (). If set to True, the data source will declare broken and permanently shut down after attempting to acquire a connection failure. The default is false;
Checkouttimeout: When the connection pool is exhausted, the client calls getconnection () to wait for a new connection, and then throws SqlException after the timeout, and waits indefinitely if set to 0. Unit milliseconds, default is 0;
Connectiontesterclassname: To test a connection by implementing a class of Connectiontester or Queryconnectiontester, the class name needs to be set to the fully qualified name. The default is Com.mchange.v2.C3P0.impl.DefaultConnectionTester;
Idleconnectiontestperiod: How many seconds to check the idle connection in all connection pools, the default is 0 means no check;
Initialpoolsize: The number of connections created at initialization should be taken between Minpoolsize and Maxpoolsize. The default is 3;
MaxIdleTime: Maximum idle time, the connection over idle time will be discarded. 0 or negative numbers will never be discarded. The default is 0;
Maxpoolsize: The maximum number of connections that are kept in the connection pool. The default is 15;
MAXSTATEMENTS:JDBC standard parameter to control the number of PreparedStatement loaded within the data source. However, because the pre-cached statement belong to a single connection instead of the entire connection pool. So setting this parameter takes many factors into account, and if both maxstatements and maxstatementsperconnection are 0, the cache is closed. The default is 0;
Maxstatementsperconnection: The maximum number of cache statement that a single connection in a connection pool has. The default is 0;
NUMHELPERTHREADS:C3P0 are asynchronous operations, and slow JDBC operations are done by helping the process. Extending these operations can effectively improve performance, and multiple operations are performed simultaneously through multithreading. The default is 3;
Preferredtestquery: Defines test statements that are executed by all connection tests. This parameter can significantly improve the test speed when using the connection test. The test table must exist at the time of the initial data source. default is null;
Propertycycle: The maximum number of seconds a user waits before modifying system configuration parameters. The default is 300;
Testconnectiononcheckout: Please use it only when you need it because of high performance consumption. If set to true then the validity of each connection submission is officer. It is recommended to use Idleconnectiontestperiod or automatictesttable
and other methods to improve the performance of the connection test. The default is false;
Testconnectiononcheckin: If set to true then the validity of the officer connection is obtained while the connection is made. The default is False.

Read the configuration file by referencing the properties:

1.<bean id= "Propertyconfigurer"
2. class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
3. <property name= "Location" value= "/web-inf/jdbc.properties"/>
4.</bean>
5.<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource"
6. Destroy-method= "Close" >
7. <property name= "Driverclassname" value= "${jdbc.driverclassname}"/>
8. <property name= "url" value= "${jdbc.url}"/>
9. <property name= "username" value= "${jdbc.username}"/>
<property name= "Password" value= "${jdbc.password}"/>
11.</bean>

To define a property value in the Jdbc.properties property file:
Jdbc.driverclassname= Com.mysql.jdbc.Driver
Jdbc.url= Jdbc:mysql://localhost:3309/sampledb
Jdbc.username=root
jdbc.password=1234
Tip developers often accidentally type some spaces before and after the ${xxx}, and the space characters are merged with the variable as the value of the property. such as: <property name= "username" value= "${jdbc.username}" ></property> of the property configuration items, before and after the space, after being parsed, the value of username is "1234 "This will cause the final error and therefore requires special care.

Get Jndi Data source
If the application is configured on a high-performance application server, such as WebLogic or WebSphere, we may prefer to use the data source provided by the application server itself. The data source for the application server is used by Jndi open callers, and spring specifically provides the Jndiobjectfactorybean class that references the Jndi resource. The following is a simple configuration:

XML code


1.<bean id= "DataSource" class= "Org.springframework.jndi.JndiObjectFactoryBean" >
2. <property name= "Jndiname" value= "JAVA:COMP/ENV/JDBC/BBT"/>
3.</bean>

Specifies the referenced Jndi data source name by Jndiname.
Spring 2.0 provides a JEE namespace for acquiring the Java EE resource, which, through the Jee namespace, effectively simplifies the reference to the Java EE resource. The following is a configuration that uses the Jee namespace to reference a Jndi data source:

XML code


1.<beans Xmlns=http://www.springframework.org/schema/beans
2.xmlns:xsi=http://www.w3.org/2001/xmlschema-instance
3.xmlns:jee=http://www.springframework.org/schema/jee
4.xsi:schemalocation= "Http://www.springframework.org/schema/beans
5.http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
6.http://www.springframework.org/schema/jee
7.http://www.springframework.org/schema/jee/spring-jee-2.0.xsd ">
8.<jee:jndi-lookup id= "DataSource" jndi-name= "JAVA:COMP/ENV/JDBC/BBT"/>
9.</beans>

Spring's data source implementation class
Spring itself also provides a simple data source implementation class Drivermanagerdatasource, which is located in the Org.springframework.jdbc.datasource package. This class implements the Javax.sql.DataSource interface, but it does not provide a mechanism for pooling connections, and it simply creates a new connection each time a call to getconnection () gets a new connection. Therefore, this data source class is better suited for use in unit testing or simple standalone applications because it does not require additional dependency classes.
Now, let's take a look at the simple use of Drivermanagerdatasource: Of course, we can also use the Drivermanagerdatasource directly in a configuration way.

Java code


1.DriverManagerDataSource ds = new Drivermanagerdatasource ();
2.ds.setdriverclassname ("Com.mysql.jdbc.Driver");
3.ds.seturl ("Jdbc:mysql://localhost:3309/sampledb");
4.ds.setusername ("root");
5.ds.setpassword ("1234");
6.Connection Actualcon = Ds.getconnection ();



Summary

Regardless of which persistence technology is used, you need to define a data source. Spring comes with an implementation class package of two data sources that you can choose to define yourself. In the actual deployment, we may be directly using the data source provided by the application server itself, at which point the data source in Jndi can be referenced through the Jndiobjectfactorybean or Jee namespace.

The difference between DBCP and C3PO configuration:

C3PO:DBCP:

XML code

1.<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method= "Close" >
2. <property name= "Driverclass" >
3. <value>oracle.jdbc.driver.OracleDriver</value>
4. </property>
5. <property name= "Jdbcurl" >
6. <value>jdbc:oracle:thin:@10.10.10.6:1521:DataBaseName</value>
7. </property>
8. <property name= "User" >
9. <value>testAdmin</value>
Ten. </property>
<property name= "Password" >
<value>123456</value>
</property>
14.</bean>

XML code

1.<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" >
2. <property name= "Driverclassname" >
3. <value>oracle.jdbc.driver.OracleDriver</value>
4. </property>
5. <property name= "url" >
6. <value>jdbc:oracle:thin:@10.10.10.6:1521:DataBaseName</value>
7. </property>
8. <property name= "username" >
9. <value>testAdmin</value>
Ten. </property>
<property name= "Password" >
<value>123456</value>
</property>
14.</bean>

Spring configuration DataSource Three ways database connection pool

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.