1. Overview of jdbctemplate
After the previous articles, we have almost finished explaining some operations of the front-end controller in SpringBoot, and experienced the convenience that SpringBoot brings us to use the framework. In all the cases in the previous article, only one web starter is introduced, and there are few configurations. Starting today, let's start to study how SpringBoot completes the data persistence operation.
Generally, the persistence operation is completed by some special persistence frameworks, such as the original JDBC, the old strong team JPA(hibernate), and the comparison or mybatis and MybatisPlus currently used. In SpringBoot, we should first select the persistence framework to be used, and then use SpringBoot for integration. The integration steps are greatly simplified due to the automatic configuration function of SpringBoot.
Today, let's start with a simpler one. Let's start with a JdbcTemplate, a persistence layer framework encapsulated by Spring based on JDBC, which is committed to lightweight and convenient operation of databases. Its operation is very simple, but it is not as comprehensive as mybatis and jpa, but it is better than native JDBC. To be honest, it is also less used in actual combat.
2. Integration steps
2.1 introducing dependencies
<!-- jdbcTemplate --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- MySQL connect --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
2.2 configuring database connections
In the configuration file of SpringBoot, configure the connection of the database, which is necessary for all databases to operate. It mainly includes the driver class used, the connection address of the database, user name, password, etc.
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot_learning username: root password: root
I created a spring boot in my local database_ The learning database is used for testing.
Then we create a user table.
CREATE TABLE `springboot_learning`.`t_user` ( `id` int(20) NOT NULL AUTO_INCREMENT COMMENT 'id', `name` varchar(40) NULL COMMENT 'full name', `age` int(20) NULL COMMENT 'Age', `address` varchar(100) NULL COMMENT 'address', `create_time` datetime(0) NULL COMMENT 'Creation time', `update_time` datetime(0) NULL COMMENT 'Update time', PRIMARY KEY (`id`) );
2.3 development entities and DAO
Create an entity folder, and then create an entity class User
@Data public class User { private Integer id; private String name; private Integer age; private String address; private Date createTime; private Date updateTime; } Copy code
The development of UserDao includes common add, delete, modify and query interfaces
UserDao interface
/** * @interface: UserDao * @description: * @author: sh.Liu * @date: 2022-01-14 16:37 */ public interface UserDao { /** * Query by id * @param id * @return */ User getUserById(Integer id); /** * Query all users * @return */ List<User> listUser(); /** * Save user * @param user * @return */ int save(User user); /** * Update user * @param id * @param user * @return */ int update(Integer id, User user); /** * delete user * @param id * @return */ int delete(Integer id); } Copy code
UserDaoImpl implementation: inject the JdbcTemplate interface into the class, which is provided by spring to operate the core objects of the database. The @ Repository annotation should also be added to this class to identify that this class is used to handle database operations. Can be scanned by spring.
The UserDaoImpl code is as follows:
package com.lsqingfeng.springboot.dao.jdbcTemplate.impl; import com.lsqingfeng.springboot.dao.jdbcTemplate.UserDao; import com.lsqingfeng.springboot.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; /** * @className: UserDaoImpl * @description: * @author: sh.Liu * @date: 2022-01-14 16:40 */ @Repository public class UserDaoImpl implements UserDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public User getUserById(Integer id) { User user = jdbcTemplate.queryForObject("select * from t_user where id = ?", new BeanPropertyRowMapper<User>(User.class), id); return user; } @Override public List<User> listUser() { List<User> users = jdbcTemplate.query("select * from t_user", new BeanPropertyRowMapper<User>(User.class)); return users; } @Override public int save(User user) { return jdbcTemplate.update("insert into t_user(name, age, address, create_time, update_time) values(?, ?, ?,?,?)", user.getName(),user.getAge(), user.getAddress(),new Date(),new Date()); } @Override public int update(Integer id, User user) { return jdbcTemplate.update("UPDATE t_user SET name = ? , age = ? ,address = ? ,update_time = ? WHERE id=?", user.getName(), user.getAge(), user.getAddress(), new Date(), id); } @Override public int delete(Integer id) { return jdbcTemplate.update("DELETE from tb_user where id = ? ",id); } } Copy code
We wrap a Service layer. At present, the mainstream project interfaces are also logic such as controller Service Dao.
2.4 Service layer development
Create a service package and add a UserService interface. The service layer is generally used to process business logic. Generally, the code with transactions is placed in this layer. It is generally divided according to the business module. The name can not be developed with the entity name or table name. It is generally used to encapsulate the operations of multiple Dao layers. If you want to fully understand the service layer, you can also need more project experience. This is mainly for demonstration, and there is no particularly complex business. We will directly name it UserService Take all the methods in Dao layer directly.
UserService
/** * @interface: UserService * @description: * @author: sh.Liu * @date: 2022-01-17 13:56 */ public interface UserService { /** * Query by id * @param id * @return */ User getUserById(Integer id); /** * Query all users * @return */ List<User> listUser(); /** * Save user * @param user * @return */ int save(User user); /** * Update user * @param id * @param user * @return */ int update(Integer id, User user); /** * delete user * @param id * @return */ int delete(Integer id); } Copy code
In the implementation class, Dao is injected directly, and the same function is realized by calling Dao.
/** * @className: UserServiceImpl * @description: * @author: sh.Liu * @date: 2022-01-17 13:56 */ @Service public class UserServiceImpl implements UserService { // This is construction method injection, which is equivalent to @ autowired private final UserDao userDao; public UserServiceImpl(UserDao userDao) { this.userDao = userDao; } @Override public User getUserById(Integer id) { return userDao.getUserById(id); } @Override public List<User> listUser() { return userDao.listUser(); } @Override public int save(User user) { return userDao.save(user); } @Override public int update(Integer id, User user) { return userDao.update(id, user); } @Override public int delete(Integer id) { return userDao.delete(id); } } Copy code
2.5 developing Controller for testing
Dao and Service are ready. Next, we will develop a Controller to test to see if we can successfully operate the database.
package com.lsqingfeng.springboot.controller; import com.lsqingfeng.springboot.base.Result; import com.lsqingfeng.springboot.entity.User; import com.lsqingfeng.springboot.exception.BizException; import com.lsqingfeng.springboot.service.UserService; import org.springframework.web.bind.annotation.*; /** * @className: JdbcController * @description: * @author: sh.Liu * @date: 2022-01-17 13:58 */ @RestController @RequestMapping("jdbc") public class JdbcController { /** * This is construction method injection, which is equivalent to @ autowired */ private final UserService userService; public JdbcController(UserService userService) { this.userService = userService; } @PostMapping("save") public Result save(@RequestBody User user){ userService.save(user); return Result.success(); } @PostMapping("update") public Result update(@RequestBody User user){ if (user.getId() == null) { throw new BizException("update operation id Cannot be empty"); } userService.update(user.getId(), user); return Result.success(); } @GetMapping("get/{id}") public Result getById(@PathVariable Integer id){ return Result.success(userService.getUserById(id)); } @GetMapping("list") public Result list(){ return Result.success(userService.listUser()); } @GetMapping("delete/{id}") public Result delete(@PathVariable Integer id){ userService.delete(id); return Result.success(); } } Copy code
We used postMan for testing. Be careful not to forget to pass the header, because our interceptor requires that the header must be passed
Return success. View the data in the database:
Data saved successfully.
Let's try the getById method again
Other methods will not be demonstrated.
3. Summary
These are the usages of the JdbcTemplate provided by Spring. The Spring method of integrating the JdbcTemplate is also relatively simple. The whole thing is to first introduce dependencies, configure the database connection, and then use the jdbc template class. Most of the database operations have been sealed in the JdbcTemplate class. Simple is simple, but this framework is rarely used in enterprise projects. It is generally used in projects with low requirements for operating the database, because it is a simple encapsulation of jdbc. All sql is written into the code, which has poor maintainability and looks messy. Later, we will continue to introduce the usage of the more mainstream DAO layer frameworks Mybatis and JPA. I hope this article is helpful to you.
In addition: the supporting project code has been managed. gitCode: gitcode.net/lsqingfeng/...
All articles will be updated in WeChat official account. Welcome to the attention: a breeze for 82 years.