Java——JDBC Template
Posted 明王不动心
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java——JDBC Template相关的知识,希望对你有一定的参考价值。
1.JDBC Template概念
为了简化持久化操作,Spring在JDBC API之上提供了JDBC Template组件。
传统操作方式:
使用JDBC Template操作方式:
JDBC Template提供统一的模板方法,在保留代码灵活性的基础上,尽量减少持久化代码。
基于JDBC的API的开发案例:
String sql = "select * from user"; Statement stmt = conn.createStatement(); ResultSet resultSet = stmt.executeQuery(sql); while (resultSet.next()){ int uid = resultSet.getInt("uid"); String name = resultSet.getString("name"); String mobile = resultSet.getString("mobile"); String addr = resultSet.getString("addr"); System.out.println(uid+" "+name+" "+mobile+" "+addr); }
基于JDBC Template的开发案例:
Integer count = jt.queryForObject("select * from user",Integer.class);
2.环境依赖
(1)依赖导入
<properties> <spring.version>4.2.4.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <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-context</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-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>
(2)bean配置
<?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 name="url" value="jdbc:mysql://148.70.251.10:3306/selection_course?useUnicode=yes&characterEncoding=utf8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
3.简单使用
1)execute方法——一般用来执行DDL语句,与表操作相关
@org.junit.Test public void testExecute(){ ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate"); jdbcTemplate.execute("create table test(id int,name varchar(32))"); }
2)update与batchUpdate方法——对数据进行增删改
将jdbcTemplate提取出来,方便后面多次利用。
private JdbcTemplate jdbcTemplate; { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate"); }
(1)update:对数据进行增删改操作
int update(String sql, Object[] args)
int update(String sql, Object... args)
@org.junit.Test public void testExecute(){ jdbcTemplate.execute("create table test(id int,name varchar(32))"); } @org.junit.Test public void testUpdate(){ String sql = "insert into student(name,sex) values(?,?)"; jdbcTemplate.update(sql,new Object[]{"ming","boy"}); }
(2)batchUpdate方法:批量增删改操作
int[] batchUpdate(String[] sql)
int[] batchUpdate(String sql, List<Object[]>)
@org.junit.Test public void testBatchUpdate(){ String[] sqls = { "insert into student(name,sex) values(\'kebi\',\'boy\')", "insert into student(name,sex) values(\'maoxian\',\'boy\')", "insert into student(name,sex) values(\'jiaqi\',\'girl\')", "insert into student(name,sex) values(\'xue\',\'girl\')", "update student set name=\'xuejiaqi\' where name=\'xue\'" }; int[] ret = jdbcTemplate.batchUpdate(sqls); System.out.println(ret); } @org.junit.Test public void testBatchUpdate2(){ String sql = "insert into selection(student,course) values(?,?)"; List<Object[]> list = new ArrayList<Object[]>(); list.add(new Object[]{2001,1001}); list.add(new Object[]{2002,1003}); int[] ret = jdbcTemplate.batchUpdate(sql, list); for (int r: ret){ System.out.println(r); //返回值1表示成功 } }
3)query与queryXXX方法——对数据进行查询操作
查询简单数据项
(1)获取一个
T queryForObject(String sql, Class<T> type)
T queryForObject(String sql, Class[] args, Class<T> type)
T queryForObject(String sql, Class<T> type, Object... args)
(2)获取多个
List<T> queryForList(String sql, Class<T> type)
List<T> queryForList(String sql, Object[] args, Class<T> type)
LIst<T> queryForList(String sql, Class<T> type, Object... args)
简单示例:
//查询单个数据 @org.junit.Test public void testQuerySimple(){ String sql = "select count(*) from student"; int count = jdbcTemplate.queryForObject(sql, Integer.class); System.out.println(count); //4 } //查询多个数据 @org.junit.Test public void testQuerySimple2(){ String sql = "select NAME from student"; List<String> names = jdbcTemplate.queryForList(sql,String.class); System.out.println(names); } //查询一个对象 @org.junit.Test public void testQueryMap(){ String sql = "select * from student where id = ?"; Map<String,Object> s =jdbcTemplate.queryForMap(sql,2001); System.out.println(s); //{id=2001, name=ming_test, sex=boy, born=null} } //查询多个对象 @org.junit.Test public void testQueryMap2(){ String sql = "select * from student"; List<Map<String,Object>> s =jdbcTemplate.queryForList(sql); System.out.println(s); // [{id=2001, name=ming_test, sex=boy, born=null}, // {id=2002, name=kebi, sex=boy, born=null}, // {id=2003, name=maoxian, sex=boy, born=null}, // {id=2005, name=xuejiaqi, sex=girl, born=null}] }
如果将查询结果进行映射了?这样方面后期的数据处理。
封装一条数据:
public void testQueryEntity(){ String sql = "select * from student where id = ?"; 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; } }, 2001); System.out.println(stu); //Student{2001,ming_test,boy,null} }
封装多条数据:
@org.junit.Test public void testQueryEntity2(){ String sql = "select * from student"; List<Student> list = 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(list); }
可以将rowmapper封装成一个对象:
@org.junit.Test public void testQueryEntity(){ String sql = "select * from student where id = ?"; Student stu = jdbcTemplate.queryForObject(sql, new StudentRowMapper(), 2001); System.out.println(stu); //Student{2001,ming_test,boy,null} } @org.junit.Test public void testQueryEntity2(){ String sql = "select * from student"; List<Student> list = jdbcTemplate.query(sql, new StudentRowMapper()); System.out.println(list); } 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持久层示例
(1)接口类
//定义student查询接口 public interface StudentDao { void insert(Student stu); void update(Student stu); void delete(int id); Student select(int id); List<Student> selectAll(); } 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+","+name+","+sex+","+born +"}"; } }
(2)持久层代码开发,之后都可以调用这里面的接口
@Repository //声明持久化对象 public 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<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; } } }
以上是关于Java——JDBC Template的主要内容,如果未能解决你的问题,请参考以下文章
Spring Boot 和 JDBCTemplate简介: JDBC Template
关于mysql驱动版本报错解决,Cause: com.mysql.jdbc.exceptions.jdbc4Unknown system variable ‘query_cache_size(代码片段