How to use JdbcTemplate with MySQL for database operations in a Spring Boot project

Show me my file first so it’s easier to explain.

1. Create a simple Spring Boot project.

What I created myself is a project of the user

public class User {
private Integer id;
private String name;
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
}
2. Configure project dependencies, including Spring Boot and MySQL connection driver.

Be sure to write it in the big tag of and then write it at the end of the tag for easy finding.

The code is as follows:
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
3. Use JdbcTemplate to create a MySQL database and design an appropriate data table.

The data.sql in the db package of resources is created as follows:

drop table if exists user;
create table user(
    id int(12) auto_increment primary key,
    namevarchar(100)
)engine=InnoDB;

Insert the user name in schema.sql in the db package of resources:

insert into user(name) values ('Hex');
insert into user(name) values ('Master');
insert into user(name) values ('He Rensi');
insert into user(name) values ('Rongguisa');
insert into user(name) values ('Niu Feier');
insert into usSer(name) values ('Haoran');
4. Write the Spring Boot configuration file and configure the connection information between JdbcTemplate and MySQL.

Note: It is possible that your database is different from my database address and name, please modify it according to the situation.

5. Create a DAO class in the project and use JdbcTemplate to complete the addition, deletion, modification and query operations of the database.

Here is how your application to the database looks like

@Service
public class UserDao {
    JdbcTemplate template;
    @Autowired
    public UserDao(JdbcTemplate template){
        this.template=template;
    }
    public List<User> getAll(){
        String sql="select * from user";
        return template.query(sql,(rs,rowNum)->{
            User entity=new User();
            entity.setId(rs.getInt("id"));
            entity.setName(rs.getString("name"));
            return entity;
        });
    }
    public User getById(Integer id){
        String sql="select * from user where id=?";
        return template.queryForObject(sql
                ,new Object[]{id}
                ,new BeanPropertyRowMapper<>(User.class));
    }
    public int add(User entity){
        String sql="insert into user(name) values(?)";
        return template.update(sql,entity.getName());
    }
    public int update(User entity){
        String sql="update user set name=? where id=?";
        return template.update(sql,entity.getName(),entity.getId());
    }
    public int delete(Integer id){
        String sql="delete from user where id=?";
        return template.update(sql,id);
    }
}
6. Create a Controller class in the project and provide corresponding interfaces to access database operations.
@RestController
@RequestMapping("/user")
public class UserController {
    UserDao dao;
    @Autowired
    public UserController(UserDao dao){
        this.dao=dao;
    }
    @RequestMapping("/list")
    public List<User> getAll(){
        return dao.getAll();
    }
    @RequestMapping("/getById/{userId}")
    public User findById(@PathVariable("userId") Integer id){
        return dao.getById(id);
    }
    @RequestMapping("/insert")
    public String insert(){
        User entity=new User();
        entity.setName("Test Username");
        return dao.add(entity)>0?"Add successfully":"fail";
    }
    @RequestMapping("/edit")
    public String edit(){
        User entity=new User();
        entity.setId(9);
        entity.setName("Test username-update");
        return dao.update(entity)>0?"Modification successful":"fail";
    }
    @RequestMapping("/delete/{userId}")
    public String delete(@PathVariable("userId") Integer id){
        return dao.delete(id)>0?"Delete successfully":"Data not found";
    }
}

7. Implement the following functions:

– Insert a piece of data into the database.

– Query all data in the database.

– Query data in the database based on conditions.

– Update data in the database.

Later I found that the above update data was a pitfall of the teacher. The update failed. Then I thought about what I had learned in class before, modified it and it worked. It can be solved in just a few sentences, just rewrite it, hahaha Ha ha

@PostMapping("/edit")
    public String edit(@RequestBody User entity){
        return dao.update(entity)>0?"Modification successful":"fail";
    }

– Delete data from the database.

The first piece of data has been deleted

Final summary:

As long as you follow the step-by-step approach every time you write a project, it will be much faster. When a bug occurs, you can also use breakpoints to find it. If you really can’t find it, just use another method to write it.