1、什么JdbcTemplate
-(1)spring框架对JDBC进行封装,使用JdbcTemplate方便实现对数据库操作
2、准备工作
- (1)引入相关jar
druid-1.1.10.jar
mysql-connector-java-5.1.7-bin.jar
spring-jdbc-5.2.6.RELEASE.jar
spring-orm-5.2.6.RELEASE.jar
spring-tx-5.2.6.RELEASE.jar
- (2)在spring配置文件配置数据库连接池
创建jdbc.properties文件
prop.driverClassName=com.mysql.cj.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/xxxx?rewriteBatchedStatements=true
prop.username=数据库账号
prop.password=数据库密码
创建bean.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:util="http://www.springframework.org/schema/util"
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/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 引入外部配置连接池 -->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${prop.driverClassName}"></property>
<property name="url" value="${prop.url}"></property>
<property name="username" value="${prop.username}"></property>
<property name="password" value="${prop.password}"></property>
</bean>
</beans>
- (3)配置JdbcTemplate对象,注入DataSource
<!-- JdbcTemplate对象 -->
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 注入dataSource -->
<property name="dataSource" ref="dataSource"></property>
</bean>
- 创建service类,创建dao类,在dao注入JdbcTemplate对象
bean.xml配置组件扫描
<!-- 组件扫描 -->
<context:component-scan base-package="com.atguigu"></context:component-scan>
service包中创建BookService
package com.atguigu.spring5.service;
import com.atguigu.spring5.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BookService {
// 注入dao
@Autowired
private BookDao bookDao;
}
dao包中创建BookDao
package com.atguigu.spring5.dao;
public interface BookDao {
}
dao包中创建BookDaoImpl
package com.atguigu.spring5.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class BookDaoImpl implements BookDao{
// 注入JdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;
}