Configuration awareness for Org.apache.commons.dbcp.BasicDataSource

Source: Internet
Author: User

For the configuration cognition of Org.apache.commons.dbcp.BasicDataSource, the configuration cognition of Org.apache.commons.dbcp.BasicDataSource "turn" 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. The DBCP data source DBCP class package is located in/LIB/JAKARTA-COMMONS/COMMONS-DBCP.JAR,DBCP is a database connection pool that relies on the Jakarta Commons-pool object pooling mechanism, so you must also include/lib/jakarta-under the Classpath commons/commons-Pool.jar. Here 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"/> <prope Rty name= "url" value= "Jdbc:mysql://localhost:3309/sampledb"/> <property name= "username" value= "root"/&gt           ; <property name= "password" value= "1234"/>Bean>Basicdatasource provides the close () method to turn off the data source, so you must set the Destroy-method=the 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, the default value istrue; Defaultreadonly: Sets whether the data source can only perform read-only operations, the default value isfalse; maxactive: Maximum connection database connection number, set to 0 o'clock, no limit, Maxidle: Maximum waiting for the number of connections, set to 0 o'clock, there is no limit, maxwait: The maximum waiting seconds, in milliseconds, more than the 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-interrupt, default isfalse; Removeabandonedtimeout: The data connection is automatically disconnected after a few seconds, the value is true in Removeabandoned, logabandoned: If the interrupt event is logged, the default isfalseThe 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/lib/c3p0/c3p0-0.9.0.4. Jar. Here is an Oracle data source configured with C3P0: XML code<bean id= "DataSource"class= "Com.mchange.v2.c3p0.ComboPooledDataSource"Destroy-method= "Close" > <property name= "driverclass" value= "Oracle.jdbc.driver.OracleDriver"/> &lt ;p roperty name= "Jdbcurl" value= "Jdbc:oracle:thin: @localhost: 1521:ora9i"/> <property name= "user" value= "a DMin "/> <property name=" password "value=" 1234 "/>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, by default, Acquireretrydelay: Two intervals in a connection, in milliseconds, and 1000 by default; 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 do anything on this test table, it will be used in the C3P0 test, the default is null, and 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. Default isfalseCheckouttimeout: When the connection pool is exhausted, the client calls getconnection () to wait for the new connection, and after the timeout, the SqlException is thrown and, if set to 0, waits indefinitely. Unit milliseconds, default 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 for idle connections in all connection pools, default to 0 means no check; Initi Alpoolsize: The number of connections created at initialization should be taken between Minpoolsize and Maxpoolsize. The default is 3, MaxIdleTime: Maximum idle time, and connections that exceed idle time are 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 the standard parameter of MAXSTATEMENTS:JDBC, which controls 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 the connection pool has. The default is 0; Numhelperthreads:c3p0 is asynchronous, and slow JDBC operations are done by the help process. Extending these operations can effectively improve performance, and multiple operations are performed simultaneously through multithreading. The 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 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 testconnectiononcheckout: Please use it only when you need it because of high performance consumption. If set to true then in each connEction submission of the time are officer to verify its effectiveness. We recommend using methods such as Idleconnectiontestperiod or automatictesttable to improve the performance of your connectivity tests. The default is false; Testconnectiononcheckin: If set to true then officer the validity of the connection while the connection is made. The default is False.  Read the configuration file by referencing the properties:<bean id= "Propertyconfigurer"class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > <property name= "Location" value = "/web-inf/jdbc.properties"/>Bean> <bean id= "DataSource"class= "Org.apache.commons.dbcp.BasicDataSource"Destroy-method= "Close" > <property name= "driverclassname" value= "${jdbc.driverclassname}"/> <prop           Erty name= "url" value= "${jdbc.url}"/> <property name= "username" value= "${jdbc.username}"/> <property name= "Password" value= "${jdbc.password}"/>Bean>to define a property value in the Jdbc.properties property file: Jdbc.driverclassname=Com.mysql.jdbc.Driver Jdbc.url= Jdbc:mysql://Localhost:3309/sampledbJdbc.username=Root Jdbc.password=1234tip 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: The property configuration item, 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 a Jndi data source if the application is configured on a high-performance application server (such as WebLogic or WebSphere, etc.), 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<bean id= "DataSource"class= "Org.springframework.jndi.JndiObjectFactoryBean" > <property name= "jndiname" value= "JAVA:COMP/ENV/JDBC/BBT "/>Bean>Specifies the referenced jndi data source name by Jndiname. Spring2. 0 A JEE namespace is provided to get the Java EE resource, and the Jee namespace can be used to simplify the reference of the Java EE resource effectively. The following is the configuration for referencing a JNDI data source using the Jee namespace: XML code<beans xmlns=http://Www.springframework.org/schema/beansXmlns:xsi=http://www.w3.org/2001/XMLSchema-instanceXmlns:jee=http://Www.springframework.org/schema/jeexsi:schemalocation= "Http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsdhttp://Www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-2.0.xsd "><jee:jndi-lookup id= "DataSource" jndi-name= "JAVA:COMP/ENV/JDBC/BBT"/>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 drivermanagerdatasource DS=NewDrivermanagerdatasource (); Ds.setdriverclassname ("Com.mysql.jdbc.Driver"); Ds.seturl ("Jdbc:mysql://localhost:3309/sampledb"); Ds.setusername ("Root"); Ds.setpassword ("1234"); Connection Actualcon=ds.getconnection (); Summary regardless of which persistence technique is used, you need to define the 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. DBCP and C3PO Configuration differences: C3po:xml code<bean id= "DataSource"class= "Com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method= "Close" > <property name= "Driverclass" > <value>oracle.jdbc.driver.OracleDrivervalue> Property> <property name= "Jdbcurl" > <value>jdbc:oracle:thin:@10.10.10.6:1521:databasenam Evalue> Property> <property name= "User" > <value>testAdminvalue> Property> <property name= "password" > <value>123456value> Property>Bean>Dbcp:xml Code<bean id= "DataSource"class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" > <property name= "Driverclassname" > <value>oracle.jdbc.driver.OracleDrivervalue> Property> <property name= "url" > <value>jdbc:oracle:thin:@10.10.10.6:1521:databasenameval Ue> Property> <property name= "username" > <value>testAdminvalue> Property> <property name= "password" > <value>123456value> Property>Bean>

Configuration awareness for Org.apache.commons.dbcp.BasicDataSource

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.