[Spring Boot] JdbcTemplate data connection template—use JdbcTemplate to operate the database

Use JdbcTemplate to operate the database

After successfully integrating JdbcTemplate in the Spring Boot project, how to use the JdbcTemplate database connection template to operate the database? Next, we will use an example to demonstrate how JdbcTemplate can implement operations such as adding, deleting, modifying, and checking student information. Let us learn and use it in practice to better understand and absorb it.

Implement student data management functions

Step 01 Create entity class.

Create the corresponding entity class Student based on the previously created Student table structure. The specific code is as follows:

public class Student {
    
    
    private Long id;
    private String name;
    private int sex;
    private int age;

    public Student() {
    
    

    }
    public Student(String name ,  int sex, int age) {
    
    
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    //省略get、set方法
}

It should be noted that the data type of the entity class must correspond one-to-one with the database field.

Step 02 Define the Repository interface.

First, create the StudentRepository interface and define the commonly used add, delete, modify, and check interface methods. The sample code is as follows:

public interface StudentRepository {
    
    
    int save(Student student);
    int update(Student student);
    int delete(Long id);
    Student findById(Long id);
}

In the above example, save(), update(), delete() and findById() methods are defined in StudentRepository.

Then, create the StudentRepositoryImpl class, inherit the StudentRepository interface, and implement the add, delete, modify, and query methods in the interface. The sample code is as follows:

@Repository
public class StudentRepositoryImpl implements StudentRepository {
    
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
}

In the above example, the @Repository annotation is used on the StudentRepositoryImpl class to annotate the data access component JdbcTemplate, and a JdbcTemplate instance is injected into the class.

Step 03: Implement the functions of adding, deleting, modifying and checking.

Next, the corresponding methods of adding, deleting, modifying, and searching are implemented one by one.

1) Newly added: Implement the save() method in the StudentRepository interface in the StudentRepositoryImpl class. The sample code is as follows:

    @Override
    public int save(Student student) {
    
    
        return jdbcTemplate.update("INSERT INTO Student(name, sex, age) values(?,?,?)",
        student.getName(),student .getSex(),student.getAge());
    }

In JdbcTemplate, in addition to querying several APIs, all new, deleted, and modified operations are completed by calling the update() method, and just pass in SQL. The return value of the Update() method is the number of rows affected by SQL execution.

2) Delete: Delete user information through user id, and implement the update() method of the StudentRepository interface in the StudentRepositoryImpl class. The sample code is as follows:

    @Override
    public int delete(Long id) {
    
    
        return jdbcTemplate.update("DELETE FROM Student where id = ? ", id);
    }

Readers may have questions after seeing this: How do you call the update() method when adding, deleting, or modifying? Is this different from other frameworks? Strictly speaking, addition, deletion, and modification all belong to data writing. Changes to the data in the database can be achieved by executing the corresponding SQL statement through update().

3) Modification: Modification is similar to new addition. Implement the update() method of the StudentRepository interface in the StudentRepositoryImpl class. The sample code is as follows:

    @Override
    public int update(Student student) {
    
    
        return jdbcTemplate.update("UPDATE Student SET name = ? , password = ? , age = ?, WHERE id=?", student.getName(), student.getSex(), student.getAge(), student.getId());
    }

4) Query: Query user information based on user id. Also implement the findById() method of the StudentRepository interface in the StudentRepositoryImpl class. The sample code is as follows:

    @Override
    public Student findById(long id) {
    
    
        return jdbcTemplate.queryForObject("SELECT * FROM Student WHERE id=?", new Object[] {
    
     id }, new BeanPropertyRowMapper<Student>(Student.class));
    }

In the above example, JdbcTemplate executes query-related statements and calls the query() method and queryForXXX() method, and the query object calls the queryForObject method. JdbcTemplate supports converting query results into entity objects and uses new BeanPropertyRowMapper(Student.class) to encapsulate the returned data. It automatically maps data columns to entity classes of specified classes through name matching.

When performing a query operation, a RowMapper is needed to match the queried columns with the attributes in the entity class one-to-one: if the column names and attribute names are the same, you can use the BeanPropertyRowMapper directly; if the column names and attribute names are different, you need Developers implement the RowMapper interface themselves to map data columns to entity class attribute fields.

Step 04 Verification test.

Next, test the encapsulated StudentRepository to see whether each method in StudentRepository is correct. Create the StudentRepositoryTests class and inject studentRepository into the test class.

@SpringBootTest
class StudentRepositoryImplTest {
    
    
    @Autowired
    private StudentRepository studentRepository;

    @Test
    void save() {
    
    
        Student student = new Student("example", 1, 30);
        studentRepository.save(student);
    }

    @Test
    void update() {
    
    
        Student student = new Student("example", 1, 18);
        student.setId(1L);
        studentRepository.update(student);
    }

    @Test
    void delete() {
    
    
        studentRepository.delete(1L);
    }

    @Test
    void findById() {
    
    
        Student student = studentRepository.findById(1L);
        System.out.println("student == " + student.toString());
    }
}

Next, execute the above unit test methods in sequence to verify whether the addition, deletion, modification and check functions of student information are normal. The results are as shown in the figure.
The results show that the unit test is executed normally, indicating that the method in StudentRepository is executed successfully, and you can also check whether the data in the database meets expectations.

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/132401787