Table of Contents
1. Spring’s own data source
2.DBCP data source
3.C3P0 data source
4.JNDI数据源
Home Java javaTutorial Detailed explanation of 4 different forms of data source configuration

Detailed explanation of 4 different forms of data source configuration

Jun 28, 2017 am 09:04 AM
spring data source

No matter what persistence technology is used, the data source needs to be defined. Spring provides 4 different forms of data source configuration methods:

spring's own data source (DriverManagerDataSource), DBCP data source, C3P0 data source, JNDI data source .

1. Spring’s own data source

DriverManagerDataSource

XML code:

<bean id="dataSource"     
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">     
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
    <property name="url" value="jdbc:oracle:thin:@172.19.34.6:1521:ORCL" />  
    <property name="username" value="orclight" />     
    <property name="password" value="123456" />  
</bean>
Copy after login

2.DBCP data source

DBCP configuration depends on 2 jar packages commons-dbcp.jar, commons-pool.jar.

XML code:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"         
        destroy-method="close">         
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
    <property name="url" value="jdbc:oracle:thin:@172.19.34.6:1521:ORCL" />  
    <property name="username" value="orclight" />     
    <property name="password" value="123456" />        
</bean>
Copy after login

Explanation of the above code:

BasicDataSource provides the close() method to close the data source, so it must be set Set the destroy-method="close" attribute so that when the Spring container is closed, the data source can be closed normally. In addition to the above necessary data source attributes, there are some commonly used attributes:
defaultAutoCommit: Set whether the connection returned from the data source uses the automatic submission mechanism, the default value is true;
defaultReadOnly: Set whether the data source only Can 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 set to 0, it means there is no limit Limitation;
maxWait: the maximum waiting seconds, in milliseconds, an error message will be reported if the time is exceeded;
validationQuery: a query SQL statement used to verify whether the connection is successful. The SQL statement must return at least one row of data, such as You can simply set it to: "select count(*) from user";
removeAbandoned: whether to self-interrupt, the default is false;
removeAbandonedTimeout: the data connection will automatically disconnect after a few seconds, removeAbandoned is true, Provide this value;
logAbandoned: whether to log interrupt events, the default is false;

3.C3P0 data source

C3P0 is an open source JDBC data source implementation project, C3P0 depends on In jar packagec3p0.jar.

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:@172.19.34.6:1521:ORCL"/>        
        <property name="user" value="orclight"/>        
        <property name="password" value="123456"/>        
    </bean>
Copy after login

ComboPooledDataSource和BasicDataSource一样提供了一个用于关闭数据源的close()方法,这样我们就可以保证Spring容器关闭时数据源能够成功释放。

    C3P0拥有比DBCP更丰富的配置属性,通过这些属性,可以对数据源进行各种有效的控制:
    acquireIncrement:当连接池中的连接用完时,C3P0一次性创建新连接的数目;
    acquireRetryAttempts:定义在从数据库获取新连接失败后重复尝试获取的次数,默认为30;
    acquireRetryDelay:两次连接中间隔时间,单位毫秒,默认为1000;
    autoCommitOnClose:连接关闭时默认将所有未提交的操作回滚。默认为false;
    automaticTestTable: C3P0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数,那么属性preferredTestQuery将被忽略。你 不能在这张Test表上进行任何操作,它将中为C3P0测试所用,默认为null;
    breakAfterAcquireFailure:获取连接失败将会引起所有等待获取连接的线程抛出异常。但是数据源仍有效保留,并在下次调   用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。默认为 false;
    checkoutTimeout:当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限期等待。单位毫秒,默认为0;
    connectionTesterClassName: 通过实现ConnectionTester或QueryConnectionTester的类来测试连接,类名需设置为全限定名。默认为 com.mchange.v2.C3P0.impl.DefaultConnectionTester; 
    idleConnectionTestPeriod:隔多少秒检查所有连接池中的空闲连接,默认为0表示不检查;
    initialPoolSize:初始化时创建的连接数,应在minPoolSize与maxPoolSize之间取值。默认为3;
    maxIdleTime:最大空闲时间,超过空闲时间的连接将被丢弃。为0或负数则永不丢弃。默认为0;
    maxPoolSize:连接池中保留的最大连接数。默认为15;
    maxStatements:JDBC的标准参数,用以控制数据源内加载的PreparedStatement数量。但由于预缓存的Statement属 于单个Connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素,如果maxStatements与 maxStatementsPerConnection均为0,则缓存被关闭。默认为0;
    maxStatementsPerConnection:连接池内单个连接所拥有的最大缓存Statement数。默认为0;
    numHelperThreads:C3P0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能,通过多线程实现多个操作同时被执行。默认为3;
    preferredTestQuery:定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个参数能显著提高测试速度。测试的表必须在初始数据源的时候就存在。默认为null;
    propertyCycle: 用户修改系统配置参数执行前最多等待的秒数。默认为300;
    testConnectionOnCheckout:因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的时候都 将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable
等方法来提升连接测试的性能。默认为false;
    testConnectionOnCheckin:如果设为true那么在取得连接的同时将校验连接的有效性。默认为false。

4.JNDI数据源

    如果应用配置在高性能的应用服务器(如WebLogic或Websphere,tomcat等)上,我们可能更希望使用应用服务器本身提供的数据源。应用服务器的数据源 使用JNDI开放调用者使用,Spring为此专门提供引用JNDI资源的JndiObjectFactoryBean类。

xml 代码:    

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">        
        <property name="jndiName" value="java:comp/env/jdbc/orclight"/>        
</bean>
Copy after login
<beans xmlns=www.springframework.org/schema/beans      xmlns:xsi=www.w3.org/2001/XMLSchema-instance      
xmlns:jee=http://www.springframework.org/schema/jee      xsi:schemaLocation="www.springframework.org/schema/beans       
www.springframework.org/schema/beans/spring-beans-2.0.xsd       
www.springframework.org/schema/jee     
www.springframework.org/schema/jee/spring-jee-2.0.xsd">        
<jee:jndi-lookup id="dataSource" jndi-name=" java:comp/env/jdbc/orclight"/>        
</beans>
Copy after login

 

The above is the detailed content of Detailed explanation of 4 different forms of data source configuration. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Power BI cannot connect, an error was encountered while trying to connect Power BI cannot connect, an error was encountered while trying to connect Feb 18, 2024 pm 05:48 PM

PowerBI may encounter difficulties when it cannot connect to a data source that is an XLS, SQL, or Excel file. This article will explore possible solutions to help you resolve this issue. This article will guide you on what to do if you encounter errors or connection failures during the connection process. So, if you are facing this problem, keep reading and we will provide you with some useful suggestions. What is the gateway connection error in PowerBI? Gateway errors in PowerBI are often caused by a mismatch between the data source information and the underlying dataset. To solve this problem, you need to ensure that the data source defined on the local data gateway is accurate and consistent with the data source specified in PowerBI desktop. PowerBI cannot connect

A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

What are the implementation methods of spring programmatic transactions? What are the implementation methods of spring programmatic transactions? Jan 08, 2024 am 10:23 AM

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

The differences and connections between Spring Boot and Spring Cloud The differences and connections between Spring Boot and Spring Cloud Jun 22, 2023 pm 06:25 PM

SpringBoot and SpringCloud are both extensions of Spring Framework that help developers build and deploy microservice applications faster, but they each have different purposes and functions. SpringBoot is a framework for quickly building Java applications, allowing developers to create and deploy Spring-based applications faster. It provides a simple, easy-to-understand way to build stand-alone, executable Spring applications

How to set transaction isolation level in Spring How to set transaction isolation level in Spring Jan 26, 2024 pm 05:38 PM

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

The 7 most commonly used annotations in Spring, the most powerful organization in history! The 7 most commonly used annotations in Spring, the most powerful organization in history! Jul 26, 2023 pm 04:38 PM

With the update and iteration of technology, Java5.0 began to support annotations. As the leading framework in Java, spring has slowly begun to abandon xml configuration since it was updated to version 2.5, and more annotations are used to control the spring framework.

Learn Spring Cloud from scratch Learn Spring Cloud from scratch Jun 22, 2023 am 08:11 AM

As a Java developer, learning and using the Spring framework is an essential skill. With the popularity of cloud computing and microservices, learning and using Spring Cloud has become another skill that must be mastered. SpringCloud is a development toolset based on SpringBoot for quickly building distributed systems. It provides developers with a series of components, including service registration and discovery, configuration center, load balancing and circuit breakers, etc., allowing developers to build micro

See all articles