1, using Org.springframework.jdbc.datasource.DriverManagerDataSource
Description: Drivermanagerdatasource to establish a connection is as long as there is a connection to create a new connection, there is no connection pool role. <bean id= "DataSource" class= "Org.springframework.jdbc.datasource.DriverManagerDataSource" > <proper Ty name= "Driverclassname" ><value>${jdbc.driverClassName}</value></property> <proper Ty name= "url" ><value>${jdbc.url}</value></property> <property name= "username" >&L t;value>${jdbc.username}</value></property> <property name= "password" ><value>${j Dbc.password}</value></property> </bean> 2. Instructions for using Org.apache.commons.dbcp.BasicDataSource: This is a kind of push Recommended data source configuration, it really uses the connection pool technology <bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" > <p
Roperty 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 nam E= "Maxidle" > <value>2</value> </property> <pro
Perty name= "maxwait" > <value>120000</value> </property>
</bean> 3. Using Org.springframework.jndi.JndiObjectFactoryBean instructions: Jndiobjectfactorybean can obtain DataSource via 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 the 3 ways does not use a connection pool, so less in the project,
The third way is to configure the data source in the Web server, which is not easy to deploy, and I recommend that you configure the data source in every two ways.
Configure a data source
Spring contains two implementation packages of data sources in third party dependencies, one of which is Apache DBCP, and the other is c3p0.
You can use either of these two configuration data sources in the spring configuration file.
dbcp Data Source
The DBCP class package is located in <spring_home></spring_home>/lib/jakarta-commons/commons-dbcp.jar,
DBCP is a database connection pool that relies on the Jakarta Commons-pool object pooling mechanism.
Therefore, the <spring_home></spring_home>/lib/jakarta-commons/commons-pool.jar must also be included in the classpath.
The following is a configuration fragment that uses DBCP to configure a MySQL data source: XML code
<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource"
destroy-method= "Close" >
< Property Name= "Driverclassname" value= "Com.mysql.jdbc.Driver"/> <property name=
"url" value= "jdbc:mysql:/ /localhost:3309/sampledb "/> <property name=" username "value=" "root"/> <property name= "password"
"value=" 1234 "/>
</bean>
Basicdatasource provides a close () method to turn off the data source, so you must set the destroy-method= the ' close ' property.
When the spring container closes, the data source shuts down properly. 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 uses an autocommit mechanism, and the default value is true;
Defaultreadonly: Sets whether the data source can only perform read-only operations, and the default value is false;
Maxactive: Maximum Connection database connection number, set to 0 o'clock, indicating no limit;
Maxidle: Number of maximum wait connections, set to 0 o'clock, indicating no limit;
Maxwait: The maximum wait seconds, the unit is milliseconds, more than time will report error message;
Validationquery: A query SQL statement that verifies the success of a connection, and the SQL statement must return at least one row of data.
If you can simply set to: "SELECT COUNT (*) from user";
Removeabandoned: Whether to break itself, the default is false;
Removeabandonedtimeout: The data connection is automatically disconnected after a few seconds, and the value is provided removeabandoned true;
Logabandoned: Whether to log interrupt events, default to false;
c3p0 Data Source
C3P0 is an open-source JDBC data source implementation project that is published with Hibernate in the Lib directory.
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. The following is the use of C3P0 to configure an Oracle data source:
XML code
<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method= "Close" >
<property name= "Driverclass" value= "Oracle.jdbc.driver.OracleDriver"/> <property name=
"Jdbcurl" value = "Jdbc:oracle:thin: @localhost: 1521:ora9i"/>
<property name= "user" value= "admin"/>
<property Name= "password" value= "1234"/>
Combopooleddatasource and Basicdatasource provide a close () method for closing the data source.
This allows the data source to be released successfully when the spring container closes.
C3P0 has a richer configuration attribute than DBCP, which enables various effective control over the data source:
Acquireincrement: The number of C3P0 to create a new connection once the connection in the connection pool is exhausted;
Acquireretryattempts: Defines the number of repeated attempts to acquire a new connection after it has failed from the database, by default of 30;
Acquireretrydelay: two times in the connection interval time, the unit millisecond, the default is 1000;
Autocommitonclose: By default, all uncommitted operations are rolled back when the connection is closed. Default to 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 do anything on this test table, it will be used in the C3P0 test, the 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 remains valid,
and continue trying to get the connection the next time you call Getconnection (). If set to True, the data source will be declared disconnected and permanently closed after the attempt to acquire the connection fails. Default to FALSE;
Checkouttimeout: When the connection pool is exhausted, the client invokes getconnection () and waits for the new connection to be fetched, and the timeout is thrown sqlexception.
If set to 0, wait indefinitely. Unit milliseconds, default to 0;
Connectiontesterclassname: Test the connection by implementing a class of Connectiontester or Queryconnectiontester, the class name needs to be set to the fully qualified name. Default is Com.mchange.v2.C3P0.impl.DefaultConnectionTester;
Idleconnectiontestperiod: Check the idle connections in all connection pools by the number of seconds, by default 0 means not checking;
Initialpoolsize: The number of connections created when initializing should be evaluated between minpoolsize and Maxpoolsize. Default is 3;
MaxIdleTime: Maximum idle time, more than idle time connection will be discarded. 0 or negative numbers will never be discarded. Default is 0;
Maxpoolsize: The maximum number of connections reserved in the connection pool. Default is 15;
MAXSTATEMENTS:JDBC standard parameter to control the number of PreparedStatement loaded in the data source.
However, because the cached statement belong to a single connection instead of the entire connection pool. So setting this parameter takes into account many factors,
If both maxstatements and maxstatementsperconnection are 0, the cache is closed. Default is 0;
Maxstatementsperconnection: The maximum number of cached statement owned by a single connection within a connection pool. Default is 0;
NUMHELPERTHREADS:C3P0 are asynchronous operations, and slow JDBC operations are accomplished through the help process. Extending these operations can effectively improve performance,
Multiple operations are executed simultaneously through multithreading. Default is 3;
Preferredtestquery: Defines the 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 initial data source. default is null;
Propertycycle: The maximum number of seconds to wait before the user modifies system configuration parameters. Default is 300;
Testconnectiononcheckout: Because of the high performance, please use it only when you need it. If set to true then the validity is officers transferred Guevara for each connection submission. Recommended use of Idleconnectiontestperiod or automatictesttable
and other methods to improve the performance of the connection test. Default to FALSE;
Testconnectiononcheckin: If set to true then officers transferred Guevara the validity of the connection while obtaining the connection. The default is False.
read the configuration file by referencing the property:
<bean id= "Propertyconfigurer"
class= " Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ">
<property name=" Location " Value= "/web-inf/jdbc.properties"/>
</bean>
<bean id= "DataSource" Org.apache.commons.dbcp.BasicDataSource "
destroy-method=" Close ">
<property name=" Driverclassname " Value= "${jdbc.driverclassname}"/>
<property name= "url" value= "${jdbc.url}"/> <property name=
" Username "value=" ${jdbc.username} "/> <property name=" password "value=
" ${jdbc.password} "/>
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 There are often developers typing some spaces before and after ${xxx}, and these space characters will be merged with the variable as the value of the property.
such as: <property name= "username" value= "${jdbc.username}" ></property> Property configuration items,
There are spaces before and after, parsed, the value of username is "1234", which will cause the final error, so you need to be particularly careful.
getting the Jndi data source
If the application is configured on a high-performance application server (such as WebLogic or WebSphere),
We might prefer to use the data source provided by the application server itself.
The application server's data source is used by Jndi-open callers, and Spring is dedicated to providing Jndiobjectfactorybean classes that reference Jndi resources.
The following is a simple configuration: XML code
<bean id= "DataSource" class= "Org.springframework.jndi.JndiObjectFactoryBean" >
<property name= " Jndiname "value=" JAVA:COMP/ENV/JDBC/BBT "/>
Specifies the name of the Jndi data source for the reference through Jndiname.
Spring 2.0 provides a JEE namespace for retrieving Java-EE resources, and can effectively simplify the reference of Java-EE resources by JEE namespaces.
The following is the configuration using the Jee namespace to reference the Jndi data Source: XML code
<beans Xmlns=http://www.springframework.org/schema/beans
xmlns:xsi=http://www.w3.org/2001/ Xmlschema-instance
Xmlns:jee=http://www.springframework.org/schema/jee
xsi:schemalocation= "http:// Www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
Http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.0.xsd " >
<jee:jndi-lookup id= "DataSource" jndi-name= "JAVA:COMP/ENV/JDBC/BBT"/>
Spring's data source implementation class
Spring itself also provides a simple data source implementation class Drivermanagerdatasource,
It is located in the Org.springframework.jdbc.datasource package. This class implements the Javax.sql.DataSource interface,
However, it does not provide a mechanism for pooling connections, and simply creates a new connection each time a getconnection () is invoked to obtain a new connection.
Therefore, this data source class is better suited for use in unit tests or simple stand-alone applications because it does not require additional dependency classes.
Next, let's take a look at the simple use of drivermanagerdatasource.
Of course, we can also use Drivermanagerdatasource directly in the way we configure it.
Java code
Drivermanagerdatasource ds = new Drivermanagerdatasource ();
Ds.setdriverclassname ("Com.mysql.jdbc.Driver");
Ds.seturl ("Jdbc:mysql://localhost:3309/sampledb");
Ds.setusername ("root");
Ds.setpassword ("1234");
Summary
No matter what persistence technology you use, you need to define a data source. Spring comes with an implementation class package of two data sources that you can choose to define.
In actual deployment, we may be directly using the data sources provided by the application server itself,
At this point, you can reference the data source in Jndi through the Jndiobjectfactorybean or Jee namespace.
The difference between DBCP and C3PO configuration:
C3po:xml Code
<bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method= "Close" >
< Property name= "Driverclass" >
<value>oracle.jdbc.driver.OracleDriver</value>
</ property>
<property name= "Jdbcurl" >
<value>jdbc:oracle:thin:@10.10.10.6:1521:d atabasename</value>
</property>
<property name= "user" >
<value>testAdmin< /value>
</property>
<property name= "password" >
<value>123456</value>
</property>
</bean>
Dbcp:xml Code
<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" >
< Property name= "Driverclassname" >
<value>oracle.jdbc.driver.OracleDriver</value>
</ property>
<property name= "url" >
<value>jdbc:oracle:thin:@10.10.10.6:1521:databasename </value>
</property>
<property name= "username" >
<value>testadmin</value >
</property>
<property name= "password" >
<value>123456</value>
</property>