Spring-JDBCTemplate(概念和准备)
JDBCTemplate
概念和准备
1.什么是JDBCTemplate?
(1)Spring框架对JDBC进行封装,使用JDBCTemplate方便实现对数据库操作
2.准备工作
(1)引入相关jar包
(2)在spring配置文件中配置数据库连接池
(3)配置jdbcTemplate对象,注入DataSource
mysqljdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode\=true&characterEncoding\=utf-8 jdbc.username=root jdbc.password=root jdbc.driverClassName=com.mysql.jdbc.Driver
jdbcbean.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:p="http://www.springframework.org/schema/p" 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"> <!-- 开启组件扫描--> <context:component-scan base-package="com.orzjiangxiaoyu.spring"></context:component-scan> <!-- 数据库连接池 --> <context:property-placeholder location="mysqljdbc.properties"></context:property-placeholder> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClassName" value="${jdbc.driverClassName}"></property> </bean> <!-- JdbcTemplate对象 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" > <!-- 注入dataSource --> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
(4)创建service类,创建dao类,在dao注入jdbcTemplate对象
package com.orzjiangxiaoyu.spring.service; import com.orzjiangxiaoyu.spring.dao.UserDao; import com.orzjiangxiaoyu.spring.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author orz * @create 2020-08-18 9:36 */ @Service public class UserService { //注入dao @Autowired private UserDao userDao; }
package com.orzjiangxiaoyu.spring.dao; import com.orzjiangxiaoyu.spring.entity.User; import java.util.List; /** * @author orz * @create 2020-08-18 9:36 */ public interface UserDao { }
package com.orzjiangxiaoyu.spring.dao; import com.orzjiangxiaoyu.spring.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.Arrays; import java.util.List; /** * @author orz * @create 2020-08-18 9:37 */ @Repository public class UserDaoImpl implements UserDao { //注入JdbcTemplate @Autowired private JdbcTemplate jdbcTemplate; }