5 配置数据库连接池相关知识点
5.1 作用
减少频繁创建、频繁释放链接、提高效率
5.2 常见的连接池
DBCP,C3P0,Druid
5.3 创建连接池
5.3.1 导入spring、数据库和连接池依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.32</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.5.RELEASE</version> </dependency>
5.3.2 创建C3p0连接池
Java
@Test //测试手动创建 c3p0 数据源 public void test1() throws Exception { ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test"); dataSource.setUser("root"); dataSource.setPassword("root"); Connection connection = dataSource.getConnection(); System.out.println(connection); connection.close(); }
思考
如何把ComboPooledDataSource对象的创建交给Spring
5.3.3 创建Druid连接池
Java
@Test //测试手动创建 druid 数据源 public void test2() throws Exception { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/test"); dataSource.setUsername("root"); dataSource.setPassword("root"); DruidPooledConnection connection = dataSource.getConnection(); System.out.println(connection); connection.close(); }
思考
如何把DruidDataSource对象的创建交给Spring
6 Spring管理连接池步骤
6.1 添加spring、数据库和连接池依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.32</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.5.RELEASE</version> </dependency>
6.2 添加jdbc.properties
注意:key的值必须要写前缀,不然可能解析不了
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=root
6.3 在spring配置中引入jdbc.properties
注意:必须先引入context命名空间
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--在spring的配置文件中引入jdbc.properties--> <context:property-placeholder location="classpath:jdbc.properties"/> </beans>
6.4 在spring配置中添加连接池配置信息
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--在spring的配置文件中引入jdbc.properties--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--在spring的配置文件中添加连接池配置信息--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans>
测试
package cn.oldlu; import com.alibaba.druid.pool.DruidDataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.sql.DataSource; import java.sql.Connection; public class C3p0Test { @Test public void test1() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = (DataSource)context.getBean("dataSource"); Connection connection = dataSource.getConnection(); System.out.println(connection); connection.close(); } }
7 案例介绍
使用spring整合mybatis技术,完成账户模块(Account)的基础增删改查功能
表结构如下
列名 | 类型 | |
id | int | 主键、自增 |
name | varchar(24) | 姓名,字符串,最多24个字符 |
money | double(10,2) | 账户余额,最大值99999999.99。小数点前最多8位,小数点后最多2位。本案例使用double类型,实际开发中使用decimal(10,2) |
8 XML方式整合
8.1第一步 引入依赖
需要引入mysql,mybatis,spring,druid连接池,以及整合mybatis和spring的依赖
<dependencies> <!--Lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.4</version> </dependency> <!--Spring核心--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.5.RELEASE</version> </dependency> <!--Spring集成Junit测试--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.5.RELEASE</version> </dependency> <!--Spring集成Aspect切面--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </dependency> <!--Spring 事物--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.5.RELEASE</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.3</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <!--spring连接数据库--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.6.RELEASE</version> </dependency> <!--数据库连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> <!--spring集成mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
8.2 第二步 创建数据库
/* SQLyog Ultimate v12.09 (64 bit) MySQL - 5.5.40 : Database - spring01 ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`spring01` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `spring01`; /*Table structure for table `account` */ DROP TABLE IF EXISTS `account`; CREATE TABLE `account` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(24) DEFAULT NULL, `money` double(10,2) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; /*Data for the table `account` */ insert into `account`(`id`,`name`,`money`) values (1,'jack',1000.00),(2,'tom',1000.00),(3,'rose',1000.00); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
8.3 第三步 创建dao\service\domain
创建实体类 Account
package cn.oldlu.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Account { private Integer id; private String name; private Double money; }
创建 Dao
package cn.oldlu.dao; import cn.oldlu.domain.Account; import java.util.List; public interface AccountDao { List<Account> findAll(); }
创建Service
package cn.oldlu.service; import cn.oldlu.domain.Account; import java.util.List; public interface AccountService { List<Account> findAll() ; }
创建Service实现类
package cn.oldlu.service.impl; import cn.oldlu.dao.AccountDao; import cn.oldlu.domain.Account; import cn.oldlu.service.AccountService; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; public class AccountServiceImpl implements AccountService { private AccountDao accountDao; public List<Account> findAll() { return accountDao.findAll(); } public AccountDao getAccountDao() { return accountDao; } public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } }
8.4 第四步 创建jdbc.properties
Properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring01 jdbc.username=root jdbc.password=root
8.5 第五步 创建mapper映射文件
映射文件的编写必须遵循下面两个原则:
该映射文件必须和dao在相同的目录(包)下,比如接口在src/cn/oldlu/dao目录下,那么配置文件也必须在resource/cn/oldlu/dao目录下。
配置文件的名字和dao接口名保持一致,这里叫AccountDao.xml。比如接口叫AccountDao.java,那么配置文件的名字必须叫AccountDao.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.oldlu.dao.AccountDao"> <!--配置查询所有--> <select id="findAll" resultType="account"> select * from account </select> </mapper>
8.6 第六步 创建 spring主配置文件
主配置文件名叫applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!--1.集成数据库连接池--> <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder> <bean id="ds" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--2.集成mybatis--> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <!--为mybatis配置数据库连接池--> <property name="dataSource" ref="ds"></property> <!--给指定包下的实体类起别名--> <property name="typeAliasesPackage" value="cn.oldlu.domain"></property> </bean> <!--3.将dao的创建交给spring容器--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--表示dao目录下的接口的实现类对象会交给spring容器管理,并且spring容器在将实现类添加到容器中的时候,会自动给id赋值,我们不需要创建实现类--> <property name="basePackage" value="cn.oldlu.dao"></property> </bean> <!--4.将service的创建交给spring容器--> <bean class="cn.oldlu.service.impl.AccountServiceImpl"> <property name="accountDao" ref="accountDao"></property> </bean> </beans>
8.7 第七步 创建测试类
public class App { public static void main(String[] args) { ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); AccountService accountService = classPathXmlApplicationContext.getBean(AccountService.class); List<Account> all = accountService.findAll(); System.out.println(all); } }
9 总结
spring报错从后往前看找自己写的错误,如果都没就是配置文件问题