In the first two articles, we talked about two things:
- Getting started with spring boot through a simple example
- Modify the default service port number and context path of spring boot
In this article, we'll look at how to persist data through JdbcTemplate.
Don't talk too much nonsense, go straight to dry goods.
I. Code Implementation
- Modify the pom file to introduce dependencies
<!-- Introduce jdbc rely on --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- Introduce mysql Database Connection Dependence--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
- Configure database information and add the following in application.properties:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root
- Create entity classes and create databases
- Entity class
package com.study.entity; public class User { private Integer id; private String userName; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
- data base
- Entity class
- Implementation of dao layer
@Repository public class UserDao { @Autowired JdbcTemplate jdbcTemplate; public void save(User user) { String sql = "insert into t_user(user_name, password) values(?,?)"; jdbcTemplate.update(sql, user.getUserName(), user.getPassword()); } }
- Implementing service Layer
- Interface
public interface UserService { public void save(User user); }
- Implementation class
@Service public class UserServiceImpl implements UserService { @Autowired UserDao userDao; public void save(User user){ userDao.save(user); } }
- Interface
- Implementing the controller layer
@RestController public class UserController { @Autowired UserService service; @RequestMapping("/saveUser") public String saveUser(User user) { service.save(user); return "save user successful"; } }
- test
- Page returns information correctly
- Correct Storage of Database
Two, summary
We find that spring boot simplifies the configuration of xml, but does not reduce the amount of java code we write.
Sprboot is not an enhancement of spring functionality, but provides a quick way to use spring: out-of-the-box, no code generation, and no XML configuration.