Spring configures datasource in three ways to connect to database

1. Use org.springframework.jdbc.datasource.DriverManagerDataSource 
Description: DriverManagerDataSource establishes a connection as long as there is a connection to create a new connection, and there is no connection pool at all. 
<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> 


<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> 















 
    Spring includes two data source implementation class packages in the third-party dependency package, one is Apache's DBCP, and the other is C3P0 . The data source can be configured using either of these in the Spring configuration file. 

DBCP data source 
    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 pool mechanism, so it must also be in the classpath Include <spring_home></spring_home>/lib/jakarta-commons/commons-pool.jar. Here is the configuration snippet for configuring MySql datasource using DBCP: 
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. <      
6. <property name="password" value="1234" />      
7. </bean>  

BasicDataSource provides a close() method to close the data source, so the destroy-method="close" attribute must be set so that the Spring container closes , the data source can be closed gracefully. In addition to the above required data source properties, there are also some commonly used properties: 
    defaultAutoCommit: set whether the connection returned from the data source adopts the automatic commit mechanism, the default value is true; 
    defaultReadOnly: set whether the data source can only perform read-only operations, The default value is false; 
    maxActive: the maximum number of database connections, when set to 0, it means there is no limit; 
    maxIdle: the maximum number of waiting connections, when it is set to 0, it means there is no limit; 
    maxWait: the maximum number of seconds to wait, in milliseconds , an error message will be reported if the time is exceeded; 
    validationQuery: The query SQL statement used to verify whether the connection is successful. The SQL statement must return at least one row of data. For example, you can simply set it as: "select count(*) from user"; 
    removeAbandoned : Whether to self-interrupt, the default is false; 
    removeAbandonedTimeout: The data connection will be automatically disconnected after a few seconds, if removeAbandoned is true, provide this value; 
    logAbandoned: Whether to record the interruption event, the default is false; 

C3P0 data source 
    C3P0 is an open source JDBC data source implementation project, which is released together with Hibernate in the lib directory, and implements the Connection and Statement pools specified by the JDBC3 and JDBC2 extension specifications. The C3P0 class package is located in <spring_home></spring_home>/lib/c3p0/c3p0-0.9.0.4.jar. The following is to configure an Oracle data source 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>  


    C3P0 has richer configuration properties than DBCP. Through these properties, various effective controls can be performed on the data source: 
    acquireIncrement: when the connections in the connection pool are used up, the number of new connections created by C3P0 at one time; 
    acquireRetryAttempts: defined in The number of repeated attempts to obtain a new connection from the database, the default is 30; 
    acquireRetryDelay: the interval between two connections, in milliseconds, the default is 1000; 
    autoCommitOnClose: When the connection is closed, all uncommitted operations are rolled back by default. The default is false; 
    automaticTestTable: C3P0 will create an empty table named Test, and use its own query statement for testing. If this parameter is defined, the property preferredTestQuery will be ignored. You can't perform any operations on this Test table, it will be used for C3P0 tests, and the default is null; 
    breakAfterAcquireFailure: Failure to acquire a connection will cause all threads waiting to acquire a connection to throw an exception. However, the data source remains valid and will continue to try to obtain a connection the next time getConnection() is called. If set to true, the data source will be declared disconnected and permanently closed after a failed connection attempt. The default is false; 
    checkoutTimeout: When the connection pool is used up, the client calls getConnection() and waits for a new connection to be obtained. After the timeout, an SQLException will be thrown. If it is set to 0, it will wait indefinitely. The unit is milliseconds, the default is 0; 
    connectionTesterClassName: Test the connection by implementing the 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 idle connections in all connection pools, the default is 0, which means no check; 
    initialPoolSize: the number of connections created during initialization, which should be between minPoolSize and maxPoolSize value between. The default is 3; 
    maxIdleTime: the maximum idle time, the connection that exceeds the idle time will be discarded. 0 or negative to never discard. The default is 0; 
    maxPoolSize: the maximum number of connections reserved in the connection pool. The default is 15; 
    maxStatements: a standard parameter of JDBC to control the number of PreparedStatements loaded in the data source. But because the pre-cached Statement belongs to a single Connection rather than the entire connection pool. So setting this parameter needs to consider many factors. If both maxStatements and maxStatementsPerConnection are 0, the cache is closed. The default is 0; 
    maxStatementsPerConnection: The maximum number of cached Statements owned by a single connection in the connection pool. Defaults to 0; 
    numHelperThreads: C3P0 operates asynchronously, and slow JDBC operations are done through helper processes. Extending these operations can effectively improve performance, enabling multiple operations to be executed simultaneously through multithreading. The default is 3; 
    preferredTestQuery: Defines the test statement that all connection tests execute. This parameter can significantly increase the test speed in the case of using the connection test. The table under test must exist at the time of the initial data source. The default is null; 
    propertyCycle: The maximum number of seconds to wait before the user modifies the system configuration parameters. The default is 300; 
    testConnectionOnCheckout: Please use it only when needed due to high performance consumption. If set to true then each connection will be checked for validity when it is submitted. It is recommended to use methods such as idleConnectionTestPeriod or automaticTestTable 
to improve the performance of connection tests. The default is false; 
    testConnectionOnCheckin: If set to true, the validity of the connection will be checked while the connection is obtained. Defaults to false. 

The way to read the configuration file refers to the property: 

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.       
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}" />      
10. <property name="password" value="${jdbc.password}" />      
11.</bean>   

    Define the 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 The 
    prompt often has The developer accidentally typed some spaces before and after ${xxx}, and these space characters will be combined with the variable as the value of the property. Such as: <property name="username" value=" 


    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 of the application server uses JNDI to open the caller to use, and Spring provides the JndiObjectFactoryBean class that references JNDI resources for this purpose. Here 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>  

Specify the referenced JNDI data source name through jndiName. 
    Spring 2.0 provides a jee namespace for obtaining J2EE resources. Through the jee namespace, the reference of J2EE resources can be effectively simplified. Here is the configuration to reference the JNDI data source using the jee namespace: 

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.     
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 The 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 pooled connections The mechanism, every time you call getConnection() to get a new connection, it simply creates a new connection. Therefore, this data source class is more suitable for use in unit tests or simple stand-alone applications, because it does not require additional dependent classes . 
     Next, let's take a look at the simple use of DriverManagerDataSource: Of course, we can also use DriverManagerDataSource directly by configuration. 

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 

    No matter what persistence technology is used, it is necessary to define the data source. Spring comes with two data source implementation class packages, you can choose to define them yourself. In actual deployment, we may directly use the data source provided by the application server itself. In this case, the data source in JNDI can be referenced through the JndiObjectFactoryBean or the 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. <  

6.        <value>jdbc:oracle:thin:@10.10.10.6:1521:DataBaseName</value>  
7.     </property>  
8.    <property name="user">  
9.        <value>testAdmin</value>  
10.    </property>  
11.    <property name="password">  
12.        <value>123456</value>  
13.    </property>  
14.</bean>  

xml 代码 

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>  
10.    </property>  
11.    <property name="password">  
12.        <value>123456</value>  
13.    </property>  
14.</bean>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325807404&siteId=291194637