JdbcTemplate简单介绍
发布日期:2021-08-21 13:17:52 浏览次数:12 分类:技术文章

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

转自:http://www.php.cn/java-article-368819.html

一、关于JdbcTemplate

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

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

Image(6)

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

二、Spring JdbcTemplate实例

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

1.创建表

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

 

1
2
3
4
create table Category (
Id int not null,
Name varchar(80) null,constraint pk_category primary key (Id)
);INSERT INTO category(id,Name) VALUES (1, '女装' );INSERT INTO category(id,Name) VALUES (2, '美妆' );INSERT INTO category(id,Name) VALUES (3, '书籍' );

 

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 " >
     <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://www.cnblogs.com/sharpest/p/8027632.html

转载地址:https://blog.csdn.net/weixin_33720078/article/details/93682200 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:普通web项目转maven项目
下一篇:Civil 3D CustomDraw .NET混合项目设置

发表评论

最新留言

感谢大佬
[***.8.128.20]2023年03月23日 05时00分42秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

最新文章

计算机信息单位中1GB等于,1gb等于多少mb 1gb换算多少mb 2019-12-02 01:43:26
机架式服务器lcd显示,DELL服务器LCD报错代码(全).doc 2019-12-02 01:43:26
iphone屏幕录制_苹果6s有屏幕录制吗 2019-12-02 01:43:26
java导出excel_Java导出excel【复制粘贴直接用】 2019-12-02 01:43:26
计算机归属应用软件的有,2017大学计算机应用基础试题附答案 2019-12-02 01:43:24
鲁大师html5测试网站,ludashi.com 2019-12-02 01:43:24
电视大学计算机网考,中央广播电视大学计算机网考题目大全 2019-12-02 01:43:24
清华大学计算机全套教程,清华大学计算机全套教程 2019-12-02 01:43:24
如何禁止某个程序修改计算机,电脑如何禁止某个程序运行? 2019-12-02 01:43:25
AD域控内计算机软件怎么升级,升级和卸载域AD:实现域网络管理一 2019-12-02 01:43:25
html 无序列表头部圆点,HTML 无序列表项目符号使用图片的CSS写法 2019-12-02 01:43:22
2021高考成绩查询入口文科,2021高考查分时间表 什么时间查成绩 2019-12-02 01:43:22
仁寿一中北校区2021高考成绩查询,四川省仁寿一中北校区2021届高三数学9月月考试题文【含答案】.pdf... 2019-12-02 01:43:22
计算机科学中的虚拟化包括哪些,什么是虚拟化? 2019-12-02 01:43:23
1404的三分之二次方用计算机怎么算,微分第二次大实验.doc 2019-12-02 01:43:23
福师大计算机应用基础期末考试A卷,计算机应用基础期末试卷A卷 2019-12-02 01:43:23
计算机应用基础 2014春季期末考核,东师2014年春季期末作业考核《计算机应用基础》... 2019-12-02 01:43:23
android动态化签名验证,Android签名机制 2019-12-02 01:43:21
timenote时光笔记+android,timenote(时光笔记) 2019-12-02 01:43:21
android关闭触摸声音,如何在Android中关闭所有触摸声音 | MOS86 2019-12-02 01:43:21