JAVA入门[18]-JdbcTemplate简单实例

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

一、关于JdbcTemplate

JdbcTemplate是最基本的Spring JDBC模板,这个模板支持简单的JDBC数据库访问功能以及基于索引参数的查询。

Spring数据访问模板:在数据库操作过程中,有很大一部分重复工作,比如事务控制、管理资源以及处理异常等,Spring的模板类处理这些固定部分。同时,应用程序相关的数据访问在回调的实现中处理,包括语句、绑定参数以及整理结果等。这样一来,我们只需关心自己的数据访问逻辑即可。

Image(6)

Spring的JDBC框架承担了资源管理和异常处理的工作,从而简化了JDBC代码,我们只需要编写从数据库读写数据的必需代码就万事大吉了。

二、Spring JdbcTemplate实例

我们的学习目标就是动手写一个demo,实现对Category的CRUD操作。

1.创建表

mysql新建数据库store,然后执行如下sql:

  db_store.sql

2.我用的IDE是IdeaIU,通过maven构建项目,通过xml配置spring。完成后的代码结构为:

Image(7)

3.创建实体类Category

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public  class  Category{
     private  int  cateId;
 
     private  String cateName;
 
     public  int  getCateId() {
         return  cateId;
     }
 
     public  void  setCateId( int  cateId) {
         this .cateId = cateId;
     }
 
     public  String getCateName() {
         return  cateName;
     }
 
     public  void  setCateName(String cateName) {
         this .cateName = cateName;
     }
 
     @Override
     public  String toString() {
         return  "id=" +cateId+ " name=" +cateName;
     }
}

  

4.修改pom.xml,引入相关依赖。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependencies>
     <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version> 4.12 </version>
     </dependency>
 
     <!-- Mysql数据库链接jar包 -->
     <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version> 5.1 . 21 </version>
         <scope>runtime</scope>
     </dependency>
</dependencies>

  

5.配置applicationContext.xml

需要配置dataSource作为jdbcTemplate的数据源。然后配置CategoryDao bean,构造注入了jdbcTemplate对象。完整的applicationContext.xml如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version= "1.0"  encoding= "UTF-8" ?>
<beans xmlns= "http://www.springframework.org/schema/beans"
        xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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/store" ></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>
     
     <bean id= "categoryDao"  class = "CategoryDao" >
         <constructor-arg ref= "jdbcTemplate" ></constructor-arg>
     </bean>
</beans>

  

6.数据访问实现类CategoryDao

CategoryDao构造函数包含了参数jdbcTemplate,然后实现了常用的数据访问操作。可以看到,我们只要关注具体的sql语句就可以了。另外,在getById()和getAll()方法中使用了lambda语法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import  org.springframework.jdbc.core.JdbcTemplate;
import  org.springframework.jdbc.core.RowMapper;
 
import  java.sql.ResultSet;
import  java.sql.SQLException;
import  java.util.List;
import  java.util.Map;
 
/**
  * Created by 陈敬 on 2017/6/6.
  */
public  class  CategoryDao {
     private  JdbcTemplate jdbcTemplate;
 
     public  CategoryDao(JdbcTemplate jdbcTemplate) {
         this .jdbcTemplate = jdbcTemplate;
     }
 
     public  int  add(Category category) {
         String sql =  "INSERT INTO category(id,name)VALUES(?,?)" ;
         return  jdbcTemplate.update(sql, category.getCateId(), category.getCateName());
     }
 
     public  int  update(Category category) {
         String sql =  "UPDATE Category SET Name=? WHERE Id=?" ;
         return  jdbcTemplate.update(sql, category.getCateName(), category.getCateId());
     }
 
     public  int  delete( int  id) {
         String sql =  "DELETE FROM Category WHERE Id=?" ;
         return  jdbcTemplate.update(sql, id);
     }
 
     public  int  count(){
         String sql= "SELECT COUNT(0) FROM Category" ;
         return  jdbcTemplate.queryForObject(sql,Integer. class );
     }
 
     public  Category getById( int  id) {
         String sql =  "SELECT Id,Name FROM Category WHERE Id=?" ;
         return  jdbcTemplate.queryForObject(sql, (ResultSet rs,  int  rowNumber) -> {
             Category category =  new  Category();
             category.setCateId(rs.getInt( "Id" ));
             category.setCateName(rs.getString( "Name" ));
             return  category;
         }, id);
     }
 
     public  List<Category> getAll(){
         String sql= "SELECT Id,Name FROM Category" ;
 
         List<Category> result=jdbcTemplate.query(sql, (resultSet, i) -> {
             Category category =  new  Category();
             category.setCateId(resultSet.getInt( "Id" ));
             category.setCateName(resultSet.getString( "Name" ));
             return  category;
         });
 
         return  result;
     }
}

  

7.测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
@ContextConfiguration (locations =  "classpath:applicationContext.xml" )
@RunWith (SpringJUnit4ClassRunner. class )
public  class  testCategoryDao {
     @Autowired
     private  CategoryDao categoryDao;
 
     @Test
     public  void  testAdd() {
         Category category =  new  Category();
         category.setCateId( 4 );
         category.setCateName( "母婴" );
 
         int  result = categoryDao.add(category);
         System.out.println(result);
     }
 
     @Test
     public  void  testUpdate() {
         Category category =  new  Category();
         category.setCateId( 4 );
         category.setCateName( "男装" );
 
         int  result = categoryDao.update(category);
         System.out.println(result);
     }
 
 
     @Test
     public  void  testGetById() {
         int  id =  4 ;
         Category category = categoryDao.getById(id);
         System.out.println(category.toString());
     }
 
     @Test
     public  void  testGetAll() {
         List<Category> categories = categoryDao.getAll();
         for  (Category item : categories) {
             System.out.println(item);
         }
     }
 
     @Test
     public  void  testCount() {
         int  count = categoryDao.count();
         System.out.println(count);
     }
 
     @Test
     public  void  testDelete() {
         int  id =  4 ;
         int  result = categoryDao.delete(id);
         System.out.println(result);
     }
}

  

完整代码:https://github.com/cathychen00/learnjava/tree/master/DemoJdbcTemplate

 


    本文转自 陈敬(Cathy) 博客园博客,原文链接http://www.cnblogs.com/janes/p/6971839.html:,如需转载请自行联系原作者



相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
2天前
|
Java 开发工具 Windows
Java入门及环境变量
Java入门及环境变量
|
2天前
|
Java API 调度
[AIGC] 深入理解Java并发编程:从入门到进阶
[AIGC] 深入理解Java并发编程:从入门到进阶
|
2天前
|
Java Nacos 开发者
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
|
2天前
|
前端开发 Java 测试技术
Java从入门到精通:4.1.1参与实际项目,锻炼编程与问题解决能力
Java从入门到精通:4.1.1参与实际项目,锻炼编程与问题解决能力
|
2天前
|
Java 程序员 数据库连接
Java从入门到精通:3.3.2性能优化与调优——内存管理篇
Java从入门到精通:3.3.2性能优化与调优——内存管理篇
Java从入门到精通:3.3.2性能优化与调优——内存管理篇
|
2天前
|
Dubbo Java 应用服务中间件
Java从入门到精通:3.2.2分布式与并发编程——了解分布式系统的基本概念,学习使用Dubbo、Spring Cloud等分布式框架
Java从入门到精通:3.2.2分布式与并发编程——了解分布式系统的基本概念,学习使用Dubbo、Spring Cloud等分布式框架
|
2天前
|
SQL Java 数据库连接
Java从入门到精通:2.3.2数据库编程——了解SQL语言,编写基本查询语句
Java从入门到精通:2.3.2数据库编程——了解SQL语言,编写基本查询语句
|
2天前
|
SQL Java 数据库连接
Java从入门到精通:2.3.1数据库编程——学习JDBC技术,掌握Java与数据库的交互
ava从入门到精通:2.3.1数据库编程——学习JDBC技术,掌握Java与数据库的交互
|
2天前
|
设计模式 存储 前端开发
Java从入门到精通:2.2.1学习Java Web开发,了解Servlet和JSP技术,掌握MVC设计模式
Java从入门到精通:2.2.1学习Java Web开发,了解Servlet和JSP技术,掌握MVC设计模式
|
2天前
|
Java API
Java从入门到精通:2.1.5深入学习Java核心技术之文件操作
Java从入门到精通:2.1.5深入学习Java核心技术之文件操作