In the first two articles we talked about two things:
- Get started with a simple instance of spring boot
- Modify the Spring boot default service port number and default context path
In this article we look at how to persist data through JdbcTemplate.
Don't say much nonsense, go straight to dry.
First, the code implementation
- Modify the Pom file to introduce dependent dependencies
<!--Introducing JDBC Dependencies - <Dependency> <groupId>Org.springframework.boot</groupId> <Artifactid>Spring-boot-starter-jdbc</Artifactid> </Dependency> <!--introducing MySQL database connection dependencies - <Dependency> <groupId>Mysql</groupId> <Artifactid>Mysql-connector-java</Artifactid> </Dependency>
- To configure the database information, add the following in Application.properties:
spring.datasource.driver-class-name=com.mysql.jdbc.driverspring.datasource.url=jdbc:mysql://localhost:3306/ Testspring.datasource.username=rootspring.datasource.password=root
- Create an entity class and create a database
- Entity class
Packagecom.study.entity; Public classUser {PrivateInteger ID; PrivateString UserName; PrivateString password; PublicInteger getId () {returnID; } Public voidsetId (Integer id) { This. ID =ID; } PublicString GetUserName () {returnUserName; } Public voidsetusername (String userName) { This. UserName =UserName; } PublicString GetPassword () {returnpassword; } Public voidSetPassword (String password) { This. Password =password; }}
View Code
- Database
- Implementing the DAO Layer
@Repository Public class Userdao { @Autowired jdbctemplate jdbctemplate; Public void Save (User user) { = "INSERT INTO T_user (user_name, password) VALUES (?,?)" ; Jdbctemplate.update (SQL, User.getusername (), User.getpassword ());} }
- Implement service layer
- interface
public interface< /span> 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); } }
- 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
- Database is saved correctly
Second, summary
As a result, spring boot simply simplifies the configuration of XML and does not reduce the amount of Java code we write.
Spring boot is not an enhancement of spring functionality, but rather provides a quick way to use spring: out of the box, without code generation, and without XML configuration.
Spring Boot Series three: Spring Boot integration JdbcTemplate