Home Database Mysql Tutorial spring中配置数据源_MySQL

spring中配置数据源_MySQL

May 30, 2016 pm 05:10 PM
data source

spring中配置数据源的几种常见方式:

 

#mysql 数据库配置(jdbc.properties)

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/databaseName?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
Copy after login

1.使用spring自带的数据源org.springframework.jdbc.datasource.DriverManagerDataSource;

方式一:

<bean id="propertyConfigurer"  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"  p:location="/WEB-INF/jdbc.properties" />

<bean id="dataSource"   class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.url}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}" />
Copy after login

p标记需要:xmlns:p="http://www.springframework.org/schema/p"

DriverManagerDataSource源码实现:

public class DriverManagerDataSource extends AbstractDriverBasedDataSource {

    public DriverManagerDataSource() {      

    }

    public DriverManagerDataSource(String url) {      
    }

    public DriverManagerDataSource(String url, String username, String password) {      
    }

    public DriverManagerDataSource(String url, Properties conProps) {      
    }

    public void setDriverClassName(String driverClassName) {     
    }

    protected Connection getConnectionFromDriver(Properties props) throws SQLException {     
    }

    protected Connection getConnectionFromDriverManager(String url, Properties props) throws SQLException {      
    }
}
Copy after login

方式二:

<bean id="dataSource"   class="org.springframework.jdbc.datasource.DriverManagerDataSource">

   <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />

  <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:ORCL" />

  <property name="username" value="root" />

  <property name="password" value="root" />

</bean> 

Copy after login

2.DBCP数据源;

DBCP(DataBase connection pool)。是 apache 上的一个 java 连接池项目,也是 tomcat 使用的连接池组件。单独使用dbcp需要2个包:commons-dbcp.jar,commons-pool.jar由于建立数据库连接是一个非常耗时耗资源的行为,所以通过连接池预先同数据库建立一些连接,放在内存中,应用程序需要建立数据库连接时直接到连接池中申请一个就行,用完后再放回去。

<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName" value="${jdbc.driverClassName}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
</bean>
Copy after login

DBCP实现:

class JdbcUtil
{
private static BasicDataSource bds;
static
{
if(bds==null)
{
bds= new BasicDataSource();
}
//分别设置数据库的连接参数
bds.setDriverClassName();
bds.setUrl();
bds.setUsername();
bds.setPassword();
}
public static Connection getConnection()
{
return bds.getConnection();
}
Copy after login

3.C3P0数据源;

C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的有Hibernate,Spring等。

依赖jar包:c3p0-0.9.1.jar、c3p0-0.9.1.2.jar、c3p0-0.9.1-pre6.jar

c3p0与dbcp区别:

dbcp没有自动回收空闲连接的功能

c3p0有自动回收空闲连接功能

<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:@localhost:1521:Test</value></property>
<property name="user"><value>root</value></property>
<property name="password"><value>root</value></property>
<!--连接池中保留的最小连接数。-->
<property name="minPoolSize" value="10" />
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="100" />
<!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="1800" />
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="3" />
<property name="maxStatements" value="1000" />
<property name="initialPoolSize" value="10" />
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="60" />
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts" value="30" />
<property name="breakAfterAcquireFailure" value="true" />
<property name="testConnectionOnCheckout" value="false" />
</bean>
Copy after login

4.JNDI数据源;

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

方式一:

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">          

    <property name="jndiName" value="java:comp/env/jdbc/bbt"/>          

</bean>
Copy after login

value值即JNDI的名称

方式二:

<bean id="queueTarget" class="org.springframework.jndi.JndiObjectTargetSource">
  <property name="jndiName">

    <value>queue/testQueue</value>
  </property>
</bean>
Copy after login

方式三:

如果不使用JndiTemplate实现InitialContext环境变量的配置,则需要jndi.properties文件(放在classpath中,一般放在src下面),内容如下

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.provider.url=jnp://localhost:1099
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
Copy after login

方式四:

使用JndiTemplate实现InitialContext环境变量的配置,例如

<bean id="queueTarget" class="org.springframework.jndi.JndiObjectTargetSource">
<property name="jndiName">
<value>queue/testQueue</value>
</property>
<property name="jndiTemplate">
<ref local="jndiTemplate"/>
</property>
</bean>
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">org.jnp.interfaces.NamingContextFactory</prop>
<prop key="java.naming.provider.url">jnp://localhost:1099</prop>
<prop key="java.naming.factory.url.pkgs">org.jboss.naming:org.jnp.interfaces</prop>
</props>
</property>
</bean>
Copy after login

 


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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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

Detailed explanation of the steps to implement batch Insert operations using MyBatis Detailed explanation of the steps to implement batch Insert operations using MyBatis Feb 22, 2024 pm 08:27 PM

Title: How to use MyBatis to implement batch Insert operations MyBatis is an excellent persistence layer framework that is widely used in Java development. In actual development, we often encounter situations where we need to insert data in batches. This article will introduce in detail how to use MyBatis to implement batch Insert operations, with specific code examples. Step 1: Configure MyBatis. Introduce MyBatis into the project and configure MyBatis related information, including database connection information, Ma

What does data source mean? What does data source mean? Jul 25, 2022 am 11:31 AM

Data source means "database or database server used by database applications"; data source is also the source of data, which is a device or original media that provides certain required data. All the information required to establish a database connection are stored in the data source. Information, by providing the correct data source name, the corresponding database connection can be found.

Data extraction in Yii framework: getting data from different data sources Data extraction in Yii framework: getting data from different data sources Jun 21, 2023 am 11:37 AM

With the rapid development of the Internet, data has become an important resource for enterprise development. In order to make better use of data, we need to extract data from different data sources for analysis and processing. In this article, we will focus on how to get data from different data sources in Yii framework. 1. Extract data from the MySQL database MySQL is one of the most popular relational databases at present. Its installation and use are very simple. Below we will introduce how to extract data from MySQL database in Yii framework

PHP PDO and ODBC: Connecting to various data sources PHP PDO and ODBC: Connecting to various data sources Feb 20, 2024 am 10:20 AM

PHPPDOPHPPDO (phpDataObjects) is an object-oriented data access abstraction layer that allows developers to connect to various database management systems (DBMS) using a unified interface. It provides a standard way to interact with a database, regardless of the underlying DBMS. Advantages of PDO: Unified interface: PDO provides a unified API for connecting, executing queries and obtaining results, thus simplifying interaction with different DBMS. PreparedStatements: PDO supports prepared statements, which helps prevent SQL injection attacks and improve performance. Transaction support: PDO allows managing transactions to ensure that database operations either all succeed or all fail. Error handling :P

How to integrate external data sources in C++ to enrich the analysis process? How to integrate external data sources in C++ to enrich the analysis process? Jun 01, 2024 pm 05:00 PM

Integrating external data sources in C++ can greatly expand data analysis capabilities. The steps include: selecting a connector that is compatible with the target data source, establishing a connection according to the data source requirements, and using SQL to query. An example of using the ODBC connector to connect to MySQL shows how to extract data results. Integrating external data sources enriches the analysis process and enables more informed decisions.

Take stock of more than 20 powerful and free data sources that anyone can use to build AI Take stock of more than 20 powerful and free data sources that anyone can use to build AI Jun 05, 2023 pm 02:29 PM

When we talk about artificial intelligence in business and society today, we’re really referring to machine learning. Machine learning is an application that uses an algorithm (a set of instructions) to become better and better at performing a specific task as it is exposed to more and more data relevant to that task. These tasks can be anything from answering questions, creating text or images (as apps like ChatGPT or Dall-E can do) to recognizing images (computer vision) or navigating a self-driving car from point A to point B. All of these tasks require data, and businesses that want to train their own machine learning algorithms to automate routine tasks will need some source of data. What types of data are there? Enterprise data is generally divided into two categories - internal data and external

How to view ODBC data sources in Win7 How to view ODBC data sources in Win7 Dec 27, 2023 am 11:35 AM

The odbc data source plays a very important role on the computer, but many users do not know how to view it, so today I will bring you the win7odbc data source viewing method. Users in need can learn it quickly. Where is the win7odbc data source: 1. Click Start in the lower left corner, and then open the "Control Panel". 2. After entering the control panel, open "Administrative Tools". 3. Then you can find the data source "odbc". 4. Double-click to view the results.

See all articles