1:为了简化持久化操作,Spring在JDBC API之上提供了JDBC Template组件,对JDBC API进行简化,基于JDBC Template操作
//JDBC Template提供统一的模板方法,在保留代码灵活性的基础上,尽量减少持久化代码
//JDBC
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery("select count(*) COUNT from student");
if(resultSet.next()){
Integer count = resultSet.getInt("COUNT");
}
//JDBC Template
Integer count = jt.queryForOject("select count(*) COUNT from student",Integer.class);
2:创建项目
Maven
-Mysql驱动
-Spring组件(core,beans,context,aop)
-JDBC Template(jdbc,tx)
Spring配置
-数据源
-JDBC Template
- 2.1Maven配置依赖
<properties>
<spring.version>4.0.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
- spring.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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/jdbctemplate?useUnicode=true&characterEncoding=utf-8"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
3:JDBC Template基本使用
- 3.1execute,用于执行DDL语句
@org.junit.Test
public void testExecute(){
//获取JDBC Template对象,对象在Spring上下文中
//Spring上下文通过配置文件构造
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
//通过bean的id获取jdbcTemplate
JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbctemplate");
//执行语句,一般是DDL语句用于execute中
jdbcTemplate.execute("create table user1(id int,name varchar(20))");
}
- 3.2update,对数据进行增删查改
public void testUpdate(){
//构造sql
String sql ="insert into student(name,sex) value(?,?)";
//update第一种是使用方式 int update(String sql,Object[] args)
jdbcTemplate.update(sql,new Object[]{"张飞","男"});
}
public void testUpdate2(){
//构造sql
String sql ="update student set sex=? where id=?";
//update语句第二种使用方式 int update(String sql,Object... args)
jdbcTemplate.update(sql,"女",1);
}
- 3.3batchUpdate,批量增删改操作
public void testBatchUpdate(){
//构造sql数组
String sqls[] = {
"insert into student(name,sex) value('Derrick','男')",
"insert into student(name,sex) value('Jessica','女')"
};
//batchupdate第一种使用方式int batchUpdate(String[] sql)
jdbcTemplate.batchUpdate(sqls);
}
public void testBatchUpdate2(){
//构造sql数组
String sql = "insert into selection(student,course) values(?,?)";
List<Object[]> list = new ArrayList<Object[]>();
list.add(new Object[]{1,1});
list.add(new Object[]{1,2});
//batchupdate第二种使用方式int batchUpdate(String sql,List<Object[]> args)
jdbcTemplate.batchUpdate(sql,list);
}
- 3.4queryForObject,获取一个数据,查询为简单对象
public void testQuery1(){
String sql = "select count(*) from student";
//获取一个
//T queryForObject(String sql,Class<T> type)
//T queryForObject(String sql,Object[] args,Class<T> type)
//T queryForObject(String sql,Class<T> type,Object arg)
int count = jdbcTemplate.queryForObject(sql,Integer.class);
System.out.println(count);
}
- 3.5queryForList,获取多个数据,查询为简单对象
public void testQuery2(){
String sql = "select name from student where sex=?";
//获取多个
//T queryForList(String sql,Class<T> type)
//T queryForList(String sql,Object[] args,Class<T> type)
//T queryForList(String sql,Class<T> type,Object arg)
List<String> names = jdbcTemplate.queryForList(sql,String.class,"女");
System.out.println(names);
}
- 3.6queryForMap,获取一个数据,封装为Map
public void testQuery3(){
String sql = "select * from student where id=?";
//获取一个
//Map queryForMap(String sql)
//Map queryForMap(String sql,Object[] args)
//Map queryForMap(String sql,Object arg)
Map<String,Object> stu = jdbcTemplate.queryForMap(sql,1);
System.out.println(stu);
}
- 3.7queryForList,获取多个数据,封装为Map
public void testQuery4(){
String sql = "select * from student";
//获取一个
//List<Map<String,Object>> queryForList(String sql)
//List<Map<String,Object>> queryForList(String sql,Object[] args)
//List<Map<String,Object>> queryForList(String sql,Object arg)
List<Map<String,Object>> stu = jdbcTemplate.queryForList(sql);
System.out.println(stu);
}
输出:
[{id=1, name=张飞, sex=女, born=null}, {id=2, name=Derrick, sex=男, born=null}, {id=3, name=Jessica, sex=女, born=null}]
- 3.8RowMapper接口进行映射,查询复杂对象(封装为实体对象)
public void testQuery5(){
String sql = "select * from student where id=?";
//获取一个
//T queryForObject(String sql,RowMapper<T> mapper)
//T queryForObject(String sql,Object[] args,RowMapper<T> mapper)
//T queryForObject(String sql,RowMapper<T> mapper,Object arg)
Student stu = jdbcTemplate.queryForObject(sql, new RowMapper<Student>() {
public Student mapRow(ResultSet resultSet, int i) throws SQLException {
//用代码组织映射关系
Student stu = new Student();
stu.setId(resultSet.getInt("id"));
stu.setName(resultSet.getString("name"));
stu.setSex(resultSet.getString("sex"));
stu.setBorn(resultSet.getDate("born"));
return stu;
}
}, 1);
System.out.println(stu);
}
public void testQuery6(){
String sql = "select * from student";
//获取多个
//List<T> query(String sql,RowMapper<T> mapper)
//List<T> query(String sql,Object[] args,RowMapper<T> mapper)
//List<T> query(String sql,RowMapper<T> mapper,Object arg)
List<Student> studentList = jdbcTemplate.query(sql, new RowMapper<Student>() {
public Student mapRow(ResultSet resultSet, int i) throws SQLException {
Student stu = new Student();
stu.setId(resultSet.getInt("id"));
stu.setName(resultSet.getString("name"));
stu.setSex(resultSet.getString("sex"));
stu.setBorn(resultSet.getDate("born"));
return stu;
}
});
System.out.println(studentList);
}
- 3.9优化:创建一个类,继承RowMapper接口,提高代码的重用性
public void testQuery5(){
String sql = "select * from student where id=?";
//获取一个
//T queryForObject(String sql,RowMapper<T> mapper)
//T queryForObject(String sql,Object[] args,RowMapper<T> mapper)
//T queryForObject(String sql,RowMapper<T> mapper,Object arg)
Student stu = jdbcTemplate.queryForObject(sql, new studentRowMapper(), 1);
System.out.println(stu);
}
@org.junit.Test
public void testQuery6(){
String sql = "select * from student";
//获取多个
//List<T> query(String sql,RowMapper<T> mapper)
//List<T> query(String sql,Object[] args,RowMapper<T> mapper)
//List<T> query(String sql,RowMapper<T> mapper,Object arg)
List<Student> studentList = jdbcTemplate.query(sql,new studentRowMapper());
System.out.println(studentList);
}
private class studentRowMapper implements RowMapper<Student>{
public Student mapRow(ResultSet resultSet, int i) throws SQLException {
Student stu = new Student();
stu.setId(resultSet.getInt("id"));
stu.setName(resultSet.getString("name"));
stu.setSex(resultSet.getString("sex"));
stu.setBorn(resultSet.getDate("born"));
return stu;
}
}
4:JDBC Template持久层示例
-注入JdbcTemplate
-声明RowMapper
- 4.1Dao层
public interface StudentDao {
void insert(Student stu);
void update(Student stu);
void delete(int id);
Student select(int id);
List<Student> selectAll();
}
public interface SelectionDao {
void insert(List<Selection> selections);
void delete(int sid,int cid);
List<Map<String,Object>> selectByStudent(int sid);
List<Map<String,Object>> selectByCourse(int cid);
}
public interface CourseDao {
void insert(Course course);
void update(Course course);
void delete(int id);
Course select(int id);
List<Course> selectAll();
}
- 4.2Dao层实现
@Repository
public class StudentDaoImpl implements StudentDao {
//如果要注入对象,则StudentDaoImpl这个对象要被Spring管理
//使用Repository注解,告诉Spring这是一个持久化对象
@Autowired
private JdbcTemplate jdbcTemplate;
public void insert(Student stu) {
String sql = "insert into student(name,sex,born) values(?,?,?)";
//jdbcTemplate自动将util的Date转化为sql的Date
jdbcTemplate.update(sql,stu.getName(),stu.getSex(),stu.getBorn());
}
public void update(Student stu) {
String sql = "update student set name=?,sex=?,born=? where id=?";
jdbcTemplate.update(sql,stu.getName(),stu.getSex(),stu.getBorn(),stu.getId());
}
public void delete(int id) {
String sql = "delete from student where id=?";
jdbcTemplate.update(sql,id);
}
public Student select(int id) {
String sql = "select * from student where id=?";
return jdbcTemplate.queryForObject(sql,new StudentRowMapper(),id);
}
public List<Student> selectAll() {
String sql = "select * from student";
return jdbcTemplate.query(sql,new StudentRowMapper());
}
private class StudentRowMapper implements RowMapper<Student> {
public Student mapRow(ResultSet resultSet, int i) throws SQLException {
Student stu = new Student();
stu.setId(resultSet.getInt("id"));
stu.setName(resultSet.getString("name"));
stu.setSex(resultSet.getString("sex"));
stu.setBorn(resultSet.getDate("born"));
return stu;
}
}
}
@Repository
public class CourseDaoImpl implements CourseDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void insert(Course course) {
String sql = "insert into course(name,score) values(?,?,?)";
//jdbcTemplate自动将util的Date转化为sql的Date
jdbcTemplate.update(sql,course.getName(),course.getScore());
}
public void update(Course course) {
String sql = "update student set name=?,score=? where id=?";
jdbcTemplate.update(sql,course.getName(),course.getScore(),course.getId());
}
public void delete(int id) {
String sql = "delete from course where id=?";
jdbcTemplate.update(sql,id);
}
public Course select(int id) {
String sql = "select * from course where id=?";
return jdbcTemplate.queryForObject(sql,new CourseRowMapper(),id);
}
public List<Course> selectAll() {
String sql = "select * from course";
return jdbcTemplate.query(sql,new CourseRowMapper());
}
private class CourseRowMapper implements RowMapper<Course> {
public Course mapRow(ResultSet resultSet, int i) throws SQLException {
Course course = new Course();
course.setId(resultSet.getInt("id"));
course.setName(resultSet.getString("name"));
course.setScore(resultSet.getInt("score"));
return course;
}
}
}
@Repository
public class SelectionDaoimpl implements SelectionDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void insert(List<Selection> selections) {
String sql = "insert into selection values(?,?,?,?)";
//将Selection转换为Object
List<Object[]> list = new ArrayList<Object[]>();
for(Selection sel:selections){
//数组长度为4,因为有4个占位符
Object[] args = new Object[4];
args[0] = sel.getSid();
args[1] = sel.getCid();
args[2] = sel.getSelTime();
args[3] = sel.getScore();
list.add(args);
}
jdbcTemplate.batchUpdate(sql,list);
}
public void delete(int sid,int cid) {
String sql = "delete from selection where student = ? and course = ?";
jdbcTemplate.update(sql,sid,cid);
}
public List<Map<String, Object>> selectByStudent(int sid) {
//连接查询
String sql = "select se.*,stu.name sname,cou.name cname from selection se " +
"left join student stu on se.student=stu.id " +
"left join course cou on se.course=cou.id "+
"where student=?";
return jdbcTemplate.queryForList(sql,sid);
}
public List<Map<String, Object>> selectByCourse(int cid) {
//连接查询
String sql = "select se.*,stu.name sname,cou.name cname from selectiocn se " +
"left join student stu on se.student=stu.id " +
"left join course cou on se.course=cou.id "+
"where course=?";
return jdbcTemplate.queryForList(sql,cid);
}
}
- 4.3 Spring.xml定义包扫描
<context:component-scan base-package="com.imooc.sc"/>