Spring DataSource Configuration

Source: Internet
Author: User

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 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/under the Classpath Jakarta-commons/commons-pool.jar. Here is a configuration fragment that uses DBCP to configure a MySQL data source:

XML code

<BeanID= "DataSource"class= "Org.apache.commons.dbcp.BasicDataSource"Destroy-method= "Close">            < Propertyname= "Driverclassname"value= "Com.mysql.jdbc.Driver" />           < Propertyname= "url"value= "Jdbc:mysql://localhost:3309/sampledb" />           < Propertyname= "username"value= "root" />           < Propertyname= "Password"value= "1234" />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/lib/c3p0/c3p0-0.9.0.4.jar. Here is an Oracle data source configured using C3P0:

XML code

<BeanID= "DataSource"class= "Com.mchange.v2.c3p0.ComboPooledDataSource"Destroy-method= "Close">           < Propertyname= "Driverclass"value= "Oracle.jdbc.driver.OracleDriver"/>           < Propertyname= "Jdbcurl"value= "Jdbc:oracle:thin: @localhost: 1521:ora9i"/>           < Propertyname= "User"value= "Admin"/>           < Propertyname= "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 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:

<BeanID= "Propertyconfigurer"class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">           < Propertyname= "Location"value= "/web-inf/jdbc.properties"/>bean><BeanID= "DataSource"class= "Org.apache.commons.dbcp.BasicDataSource"Destroy-method= "Close">           < Propertyname= "Driverclassname"value= "${jdbc.driverclassname}" />           < Propertyname= "url"value= "${jdbc.url}" />           < Propertyname= "username"value= "${jdbc.username}" />           < Propertyname= "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/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: The property configuration item, before and after the space, after being parsed, the value of username is "1234", which will cause the final error, so you need special care.

Spring DataSource Configuration

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.