Using jdbctemplate in spring to operate database (add, delete, modify and batch operation) with source code explanation [super detailed]

osc_ 3aqbiyys 2021-01-21 11:39:06
using jdbctemplate spring operate database


JdbcTemplate summary

Spring Frame pair JDBC encapsulate , Use JdbcTemplate It is convenient to operate the database .

JdbcTemplate preparation

To introduce the relevant jar package

 Insert picture description here

To configure xml The configuration file

stay spring Profile configuration database connection pool , To configure JdbcTemplate object , Inject DataSource. Reference external configuration file is used for configuration , So we need to import external property files , At the same time, object creation is based on annotation, so component scanning should also be turned on .

bean1.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:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Turn on component scanning -->
<context:component-scan base-package="com.Keafmd"></context:component-scan>
<!-- Import external property file -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- Configure connection pool -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.url}" ></property>
<property name="username" value="${jdbc.username}" ></property>
<property name ="password" value="${jdbc.password}" ></property>
</bean>
<!-- establish jdbcTemplate object -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- Inject DataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>

jdbc.properties:

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/user_db?characterEncoding=utf8&useUnicode=true&useSSL=false
jdbc.username=root
jdbc.password=root

JdbcTemplate Operating the database

Related operations and comments are in the code , Please look at the code. .

Get the database ready uset_db Create a t_user surface

 Insert picture description here

Corresponding database creation User Entity class

User class :

package com.Keafmd.spring5.entity;
/**
* Keafmd
*
* @ClassName: User
* @Description: Database correspondence user Entity class
* @author: Cowherd Conan
* @date: 2021-01-19 10:07
*/
public class User {

private String userId;
private String username;
private String ustatus;
public User() {

}
public User(String userId, String username, String ustatus) {

this.userId = userId;
this.username = username;
this.ustatus = ustatus;
}
public void setUserId(String userId) {

this.userId = userId;
}
public void setUsername(String username) {

this.username = username;
}
public void setUstatus(String ustatus) {

this.ustatus = ustatus;
}
public String getUserId() {

return userId;
}
public String getUsername() {

return username;
}
public String getUstatus() {

return ustatus;
}
@Override
public String toString() {

return "User{" +
"userId='" + userId + '\'' +
", username='" + username + '\'' +
", ustatus='" + ustatus + '\'' +
'}';
}
}

establish UserDao Interface and create UserDaoImpl class

stay UserDaoImpl Class injection jdbcTemplate.

UserDao Interface :

package com.Keafmd.spring5.dao;
import com.Keafmd.spring5.entity.User;
import java.util.List;
/**
* Keafmd
*
* @ClassName: UserDao
* @Description:
* @author: Cowherd Conan
* @date: 2021-01-19 9:56
*/
public interface UserDao {

// Add method 
void add(User user);
// Modification method 
void updateUser(User user);
// Delete method 
void delete(String id);
// Number of query records 
int selectCount();
// Query return object 
User findUserInfo(String id);
// Query the collection 
List<User> findAllUser();
// Batch addition 
void batchAddUser(List<Object[]> batchArgs);
// Bulk changes 
void batchUpdateUser(List<Object[]> batchArgs);
// Batch deletion 
void batchDeleteUser(List<Object[]> batchArgs);
}

UserDaoImpl class :

package com.Keafmd.spring5.dao;
import com.Keafmd.spring5.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.Arrays;
import java.util.List;
/**
* Keafmd
*
* @ClassName: UserDaoImpl
* @Description: UserDao Implementation class
* @author: Cowherd Conan
* @date: 2021-01-19 9:56
*/
@Repository
public class UserDaoImpl implements UserDao {

// Inject jdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;
// How to add 
@Override
public void add(User user) {

// establish sql sentence 
String sql=" INSERT INTO t_user (user_id, username, ustatus) VALUES (?, ?, ?) ";
// Call method implementation 
int updat = jdbcTemplate.update(sql,user.getUserId(),user.getUsername(),user.getUstatus());
// Returns the number of successful entries 
System.out.println(updat);
}
// modify 
@Override
public void updateUser(User user) {

String sql = "UPDATE user_db.t_user SET username = ?, ustatus = ? WHERE user_id = ?";
Object[] args = {
user.getUsername(),user.getUstatus(),user.getUserId()};
int updat = jdbcTemplate.update(sql,args);
System.out.println(updat);
}
// Delete 
@Override
public void delete(String id) {

String sql ="DELETE FROM user_db.t_user WHERE user_id = ?";
int updat = jdbcTemplate.update(sql,id);
System.out.println(updat);
}
// Number of query records 
@Override
public int selectCount() {

String sql ="SELECT COUNT(*) FROM t_user";
Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
return count;
}
// Returns the object 
@Override
public User findUserInfo(String id) {

String sql ="SELECT * FROM t_user where user_id = ?";
User user = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),id);
return user;
}
// Returns the collection object 
@Override
public List<User> findAllUser() {

String sql = "select * from t_user";
List<User> userList =jdbcTemplate.query(sql,new BeanPropertyRowMapper<User>(User.class));
return userList;
}
// Batch addition 
@Override
public void batchAddUser(List<Object[]> batchArgs) {

String sql=" INSERT INTO t_user (user_id, username, ustatus) VALUES (?, ?, ?) ";
int []ints = jdbcTemplate.batchUpdate(sql,batchArgs);
System.out.println(Arrays.toString(ints));
}
// Bulk changes 
@Override
public void batchUpdateUser(List<Object[]> batchArgs) {

String sql = "UPDATE user_db.t_user SET username = ?, ustatus = ? WHERE user_id = ?";
int []ints = jdbcTemplate.batchUpdate(sql,batchArgs);
System.out.println(Arrays.toString(ints));
}
// Batch deletion 
@Override
public void batchDeleteUser(List<Object[]> batchArgs) {

String sql ="DELETE FROM user_db.t_user WHERE user_id = ?";
int []ints = jdbcTemplate.batchUpdate(sql,batchArgs);
System.out.println(Arrays.toString(ints));
}
}

establish UserService Class and inject UserDao

UserService class :

package com.Keafmd.spring5.service;
import com.Keafmd.spring5.dao.UserDao;
import com.Keafmd.spring5.dao.UserDaoImpl;
import com.Keafmd.spring5.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Keafmd
*
* @ClassName: BookService
* @Description:
* @author: Cowherd Conan
* @date: 2021-01-19 9:55
*/
@Service
public class UserService {

// Inject dao
@Autowired
private UserDao userDao;
// How to add 
public void addUser(User user){

userDao.add(user);
}
// The method of modification 
public void updateUser(User user){

userDao.updateUser(user);
}
// Delete method 
public void deleteUser(String id){

userDao.delete(id);
}
// Number of records in the query table 
public int findCount(){

return userDao.selectCount();
}
// Query return object 
public User findOne(String id){

return userDao.findUserInfo(id);
}
// Query return collection 
public List<User> findAll(){

return userDao.findAllUser();
}
// Batch addition 
public void batchAdd(List<Object[]> batchArgs){

userDao.batchAddUser(batchArgs);
}
// Bulk changes 
public void batchUpdate(List<Object[]> batchArgs){

userDao.batchUpdateUser(batchArgs);
}
// Batch deletion 
public void batchDelete(List<Object[]> batchArgs){

userDao.batchDeleteUser(batchArgs);
}
}

Write a test class to test

TestUser :

package com.Keafmd.spring5.test;
import com.Keafmd.spring5.entity.User;
import com.Keafmd.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.ArrayList;
import java.util.List;
/**
* Keafmd
*
* @ClassName: TestUser
* @Description:
* @author: Cowherd Conan
* @date: 2021-01-19 10:35
*/
public class TestUser {

@Test
public void testJdbcTemplate(){

ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = context.getBean("userService", UserService.class);
// add to 
/*User user = new User("001","Keafmd","11");
userService.addUser(user);*/
// to update 
/*User user1 = new User("001","Keafmd","2");
userService.updateUser(user1);*/
// Delete 
/*String id = "2";
userService.deleteUser(id);*/
// Return the total number 
int count = userService.findCount();
System.out.println(count);
// Returns the object 
User user = userService.findOne("1");
System.out.println(user);
// Returns the collection object 
List<User> userList =userService.findAll();
System.out.println(userList);
// Batch addition 
/*List<Object[]> batchArgs = new ArrayList<>();
Object[]o1 = {"7","77","7"};
Object[]o2 = {"8","88","8"};
Object[]o3 = {"9","99","9"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
userService.batchAdd(batchArgs);*/
// Bulk changes 
/*List<Object[]> batchArgs = new ArrayList<>();
Object[]o11 = {"tt","2","7"};
Object[]o22 = {"uu","2","8"};
Object[]o33 = {"ii","2","9"};
batchArgs.add(o11);
batchArgs.add(o22);
batchArgs.add(o33);
userService.batchUpdate(batchArgs);*/
// Batch deletion 
List<Object[]> batchArgs = new ArrayList<>();
Object[]o1 = {
"7"};
Object[]o2 = {
"8"};
Object[]o3 = {
"9"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
userService.batchDelete(batchArgs);
}
}

Output results :

 January 19, 2021 4:05:28 Afternoon com.alibaba.druid.pool.DruidDataSource info
Information : {
dataSource-1} inited
9
User{
userId='1', username='Keafmd', ustatus='2'}
[User{
userId='1', username='Keafmd', ustatus='2'}, User{
userId='2', username='aa', ustatus='1'}, User{
userId='3', username='bb', ustatus='1'}, User{
userId='4', username='cc', ustatus='1'}, User{
userId='5', username='dd', ustatus='1'}, User{
userId='6', username='ee', ustatus='1'}, User{
userId='7', username='tt', ustatus='2'}, User{
userId='8', username='uu', ustatus='2'}, User{
userId='9', username='ii', ustatus='2'}]
[1, 1, 1]
Process finished with exit code 0

 Insert picture description here

The top two red lines are log information , It's not a mistake , Never mind .

JdbcTemplate Source code interpretation

jdbcTemplate.update( Add, delete and change operation )

Invoked in additions and deletions jdbcTemplate.update(sql,id); There are two parameters in .
Source code :

public int update(String sql, @Nullable Object... args) throws DataAccessException {

return this.update(sql, this.newArgPreparedStatementSetter(args));
}

The first parameter :sql sentence .
The second parameter : Variable parameters , Set up sql Statement value .

jdbcTemplate.queryForObject( Returns the number of records )

Invoked in query record number operations jdbcTemplate.queryForObject(sql,Integer.class); There are two parameters in .

Source code :

public <T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException {

return this.queryForObject(sql, this.getSingleColumnRowMapper(requiredType));
}

Two parameters :
The first parameter :sql sentence .
The second parameter : Return type Class.

jdbcTemplate.queryForObject( Returns the object )

Invoked in the returned object jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper(User.class),id); There are three parameters in .
Source code :

public <T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args) throws DataAccessException {

List<T> results = (List)this.query((String)sql, (Object[])args, (ResultSetExtractor)(new RowMapperResultSetExtractor(rowMapper, 1)));
return DataAccessUtils.nullableSingleResult(results);
}

There are three parameters :
The first parameter :sql sentence .
The second parameter :RowMapper It's the interface , For different types of data returned , Use the implementation class in this interface to complete data encapsulation .
The third parameter :sql Statement value .


jdbcTemplate.query( Returns a collection of objects )

Invoked in the collection of returned objects jdbcTemplate.query(sql,newBeanPropertyRowMapper(User.class)); There are two parameters in .

Source code :

public <T> List<T> query(String sql, RowMapper<T> rowMapper) throws DataAccessException {

return (List)result(this.query((String)sql, (ResultSetExtractor)(new RowMapperResultSetExtractor(rowMapper))));
}

There are two parameters :
The first parameter :sql sentence .
The second parameter :RowMapper It's the interface , For different types of data returned , Use the implementation class in this interface to complete data encapsulation .

jdbcTemplate.batchUpdate( The batch operation )

Invoked in batch operation jdbcTemplate.batchUpdate(sql,batchArgs); There are two parameters .

Source code :

public int[] batchUpdate(String sql, List<Object[]> batchArgs) throws DataAccessException {

return this.batchUpdate(sql, batchArgs, new int[0]);
}

There are two parameters :
The first parameter :sql sentence .
The second parameter :List aggregate , Add multiple record data .

That's all Spring Use in JdbcTemplate Operating the database ( Add, delete, change and query and batch operation ) With the full content of the source code explanation .

If it helps you , Thank you for your support !
If you're on the computer side , See the one in the lower right corner “ One key, three links ” Did you? , That's right. Point it [ ha-ha ]

 Insert picture description here

come on. !

Joint efforts !

Keafmd

版权声明
本文为[osc_ 3aqbiyys]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210121113704807h.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云