博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring JDBCTemplate学习笔记
阅读量:5117 次
发布时间:2019-06-13

本文共 7815 字,大约阅读时间需要 26 分钟。

为了简化持久化操作,Spring在JDBC API之上提供了JDBC Template组件,JDBC Template提供统一的模板方法,在保留代码灵活性的基础上,尽量减少持久化代码。

 下面介绍JDBC Template基本使用

新建student表与实体类字段一样

—execute方法:一般用来操作ddl语句

@Testpublic void demo1(){ //execute方法,一般用来操作DDL语句    String sql = "create table customer (id int,name varchar(20))";    jdbcTemplate.execute(sql);}

—update方法

@Test public void demo2(){ //update方法,对数据库进行增删改操作     String sql = "insert into student(name,sex) values (?,?)";     jdbcTemplate.update(sql,"赵信","男"); } @Test public void demo3(){ //update方法,对数据库进行增删改操作     String sql = "update student set sex = ? where id = ?";     jdbcTemplate.update(sql,new Object[]{"女",2}); }

—batchUpdate方法

@Testpublic void demo4(){ //batchUpdate方法,批量增删改操作    String[] sqls = {"insert into student (name,sex) values ('发条魔灵','女')" ,                     "insert into student (name,sex) values ('辛德拉','女')" ,                     "update student set sex = '男',name = 'EZ' where id = 2"};    jdbcTemplate.batchUpdate(sqls);}@Testpublic void demo5(){ //batchUpdate方法,批量增删改操作    String sql = "insert into selection (student,course) values(?,?)";    List
list = new ArrayList
(); list.add(new Object[]{1,1001}); list.add(new Object[]{2,1001}); list.add(new Object[]{2,1002}); list.add(new Object[]{2,1003}); jdbcTemplate.batchUpdate(sql,list);}

—query方法:返回Map和实体类这两种使用的比较多

@Testpublic void demo6(){ //查询简单数据项,获取一个    String sql = "select name from student where id = ?";    String name = jdbcTemplate.queryForObject(sql,String.class,1);    System.out.println("姓名:"+name);}@Testpublic void demo7(){ //查询简单数据项,获取多个    String sql = "select name from student where sex = ?";    List
names = jdbcTemplate.queryForList(sql,String.class,"女"); System.out.println(names);}@Testpublic void demo8(){ //查询复杂对象(封装为Map) 获取一个 String sql = "select * from student where id = ?"; Map
stu = jdbcTemplate.queryForMap(sql,2); System.out.println(stu);}@Testpublic void demo9(){ //查询复杂对象(封装为Map) 获取多个 String sql = "select * from student"; List
> stus = jdbcTemplate.queryForList(sql); System.out.println(stus);}@Testpublic void demo10(){ //查询复杂对象(封装为实体对象) 获取一个 需使用RowMapper接口 String sql = "select * from student where id = ?"; Student stu = jdbcTemplate.queryForObject(sql,new StudentRowMapper(),4); System.out.println(stu.toString());}@Testpublic void demo11(){ //查询复杂对象(封装为实体对象) 获取多个 需使用RowMapper接口 String sql = "select * from student"; List
stus = jdbcTemplate.query(sql,new StudentRowMapper()); System.out.println(stus);} private class StudentRowMapper implements RowMapper
{ 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; }}

以上是语法使用,下面以Student表为例简单写一套持久层案例

实体类:Student.java

package com.cj.sc.entity;import java.util.Date;public class Student {    private int id;    private String name;    private String sex;    private Date born;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public Date getBorn() {        return born;    }    public void setBorn(Date born) {        this.born = born;    }    @Override    public String toString() {        return "Student{" +                "id=" + id +                ", name='" + name + '\'' +                ", sex='" + sex + '\'' +                ", born=" + born +                '}';    }}

接口类:StudentDao.java

package com.cj.sc.dao;import com.cj.sc.entity.Student;import java.util.List;public interface StudentDao {    void insert(Student stu);    void update(Student stu);    void delete(int id);    Student select(int id);    List
selectAll();}

接口实现类:StudentDaoImpl.java

package com.cj.sc.dao.impl;import com.cj.sc.dao.StudentDao;import com.cj.sc.entity.Student;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;import org.springframework.stereotype.Repository;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;@Repositorypublic class StudentDaoImpl implements StudentDao{    @Autowired    private JdbcTemplate jdbcTemplate;    public void insert(Student stu) {        String sql = "insert into student(name,sex,born) values(?,?,?)";        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
selectAll() { String sql = "select * from student"; return jdbcTemplate.query(sql,new StudentRowMapper()); } private class StudentRowMapper implements RowMapper
{ 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; } }}

配置文件:spring.xml

测试类:JDBCTemplateDemo2.java

import com.cj.sc.dao.StudentDao;import com.cj.sc.dao.impl.StudentDaoImpl;import com.cj.sc.entity.Student;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:spring.xml")public class JDBCTemplateDemo2 {    @Autowired    private StudentDao studentDao;    @Test    public void demo1() throws ParseException {        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");        String d = "1992-06-10 05:10:49";        Date born = df.parse(d);        Student stu = new Student();        stu.setName("劫");        stu.setSex("男");        stu.setBorn(born);        studentDao.insert(stu);    }    @Test    public void demo2(){        Student stu = new Student();        stu.setId(2);        stu.setName("VN");        stu.setSex("女");        studentDao.update(stu);    }    @Test    public void demo3(){        studentDao.delete(5);    }    @Test    public void demo4(){        Student stu = studentDao.select(6);        System.out.println(stu);    }    @Test    public void demo5(){        List
stus = studentDao.selectAll(); System.out.println(stus); }}

这样就简单实现了持久层的增删改查

优点:

——使用最少的代码和配置完成功能实现

——简单、灵活

缺点:

——数据库代码写在JAVA程序中,不方便管理

——功能不丰富(例如对象里面包含对象这种处理比较麻烦,不如mybatis直接配置文件中写映射关系)

源码demo链接:   密码:0u9s

转载于:https://www.cnblogs.com/cuijiade/p/9717145.html

你可能感兴趣的文章
java面试题
查看>>
提高码力专题(未完待续)
查看>>
pair的例子
查看>>
前端框架性能对比
查看>>
@property中 retain 详解
查看>>
uva 387 A Puzzling Problem (回溯)
查看>>
12.2日常
查看>>
同步代码时忽略maven项目 target目录
查看>>
MVC.NET:提供对字体文件.woff的访问
查看>>
Oracle中包的创建
查看>>
团队开发之个人博客八(4月27)
查看>>
发布功能完成
查看>>
【原】小程序常见问题整理
查看>>
C# ITextSharp pdf 自动打印
查看>>
【Java】synchronized与lock的区别
查看>>
django高级应用(分页功能)
查看>>
【转】Linux之printf命令
查看>>
关于PHP会话:session和cookie
查看>>
Chrome development tools学习笔记(3)
查看>>
软件过程的守护神
查看>>