[Spring Boot] Use MyBatis annotations to implement database operations

Use MyBatis annotations to implement database operations

MyBatis also provides an annotation method. Compared with the XML method, the annotation method is simpler and more convenient, and there is no need to create an XML configuration file. Next, take a closer look at how to use annotations.

1. Similarities and differences between XML and annotations

1) The annotation mode is easy to use and has high development efficiency, but it is troublesome to maintain. Modifying the SQL requires recompiling and packaging.

2) XML mode is easy to maintain, SQL and code are separated, and the code is clear and easy to understand. However, using annotation mode requires adding various annotations and SQL statements before the method, making the code less readable.

3) Although XML mode provides complete tags to implement complex SQL statements, it is not as simple and convenient as directly judging splicing in Java code.

4) XML mode: Because SQL is configured in an XML file, some special characters need to be escaped, so it is troublesome to use and error-prone.

2. Use MyBatis annotations to implement data query

The biggest feature of MyBatis annotation mode is that the XML configuration of Mapper is cancelled. SQL statements are defined in the Mapper interface method or the method of SQLProvider through @Insert, @Update, @Select, @Delete and other annotations, thus eliminating the need for XML configuration. document. The use of these annotations and parameters is basically consistent with the mapper.xml configuration file. Let's demonstrate the use of MyBatis annotations to implement data query.

2.1 Modify configuration file

First create a Spring Boot project, and the process of integrating MyBatis is the same as XML configuration.

To use the annotation method, you only need to specify the package path of the entity class in application.properties, and the others remain unchanged. The configuration example is as follows:

#mapper.xml mapper接口的包路径
MyBatis.type-aliases-package=com.example.ysxq

#数据库连接
spring.datasource.url=jdbc:mysql://Localhost:3306/ceshi?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

In the above example, the package path and data source of the mapper interface are configured, and there is no need to configure the path of the mapper.xml file.

2.2 Add mapper interface

Using the SQL statement annotations provided by MyBatis does not require creating a mapper.xml mapping file, creating a mapper interface class, and then adding related methods:

public interface StudentMapper {
    
    
    @Select("select * from student")
    List<Student> selectAll();
}

In the above example, using the @Select annotation to define the SQL query statement can realize the function of querying the list of all students, without defining the mapper.xml mapping file.

2.3 Verification test

Add a unit test method to verify whether it takes effect. The sample code is as follows:

@Test
    public void testSelectAll() {
    
    
        // 查询
        List<Student> students = studentMapper.selectAll();
        for (Student stu : students) {
    
    
            System.out.println("name:"+stu.getName()+", age:"+stu.getAge());
        }
    }

Click Run Test or right-click on the method and select Run 'testSelectAll' to view the unit test results. The running results are as shown in the figure.

Insert image description here
The results show that the unit test method testSelectAll runs successfully and the corresponding query results are output. This shows that the function of querying all student information has been successfully implemented using annotations.

3.Parameter passing

I believe many people will have questions: How does MyBatis pass parameters to SQL? What are the different ways to pass parameters? Let’s introduce the parameter passing methods of MyBatis annotations one by one.

3.1 Directly passing parameters

For simple parameters, you can directly use #{id} to receive variable parameters with the same name. The sample code is as follows:

@Select("SELECT * FROM student where id=#{id,jdbcType=VARCHAR}")
Student selectOne(Long id);

In the above example, use #{id} to pass in variable parameters, which supports passing in multiple parameters. Just note that the parameter names defined using #{} must be consistent with the parameter names in the method.

3.2 Use @Param annotation

The function of the @Param annotation is to name the parameters. After the parameters are named, the parameter values ​​can be matched according to the names and the parameters can be correctly passed into the SQL statement. For example, if the annotation is @Param("person"), then the parameter will be named #{person}. The sample code is as follows:

@Select("select * from student where name=#{name} and sex=#{sex}")
Student selectByNameAndSex(@Param("name") String name, @Param("sex") Integer sex);

If the method has multiple parameters, you do not need to customize param. MyBatis can give them custom names on the parameters of the method. The parameters are first prefixed with "param", and their parameter positions are added as parameter aliases. For example, #{param1}, #{param2}.

// 默认使用param +参数序号或者0、1,值就是参数的值
@Select("select * from student where name=#{param1} and sex=#{param2}")
Student selectByNameAndSex(String name, Integer sex);

If you don't want to name each parameter, you can use the param parameter. The default format is param+parameter number or 0, 1, and the value is the value of the parameter.

3.3 Mapping value transfer

When multiple parameters need to be transmitted, you can also consider using the map form.

@Select("select * from student where name=#{name} and sex=#{sex}")
Student selectByNameAndSex(Map<String, Object> map);

In the above example, the parameters required by the SQL statement are passed in through the map type, key is the parameter name, and value is the parameter value. MyBatis will automatically match the parameter values ​​in the corresponding mapping.

When calling, just add the parameters to the mapping in sequence:

@Map param= new HashMap();
param.put("name", "ysxq");
param.put("sex", 1);
Student student = studentMapper.selectByNameAndSex(param);

3.4 Using pojo objects

Using the pojo object to pass parameters is a common method of passing parameters. Methods such as insert and update introduced earlier all directly pass in the user object.

@Update({
    
    
     "update student",
     "set name = #{name,jdbcType=VARCHAR},",
     "age = #{age,jdbcType=INTEGER},",
     "sex = #{sex,jdbcType=INTEGER}",
     "where id =#{id,jdbcType=VARCHAR}"
})
void update(Student record);

For methods with many parameters such as insert and update, you can use pojo objects to pass parameters. It should be noted that the name and type of the parameter must be consistent with the properties of the pojo object.

The above describes the four ways of passing parameters in MyBatis. When using it, just choose the appropriate value passing method according to the parameters of the method.

4. Result mapping

MyBatis will automatically convert the query result set into the data type that needs to be returned, but there are some special scenarios that need to be handled. For example, what should be done when the query return results are inconsistent with the expected data format?

This requires the use of @Results and @Result annotations. These two annotations can convert the values ​​queried in the database into specific attributes or types, and modify the returned result set. For example, the attribute name of the query object's return value is inconsistent with the field name, or enumerations are used in the object's attributes, etc.

    @Select({
    
    
            "select",
            "id, name as student_name,age, sex as student_sex",
            "from student",
            "where id = #{id,jdbcType=VARCHAR}"
    })
    @Results({
    
    
            @Result(column="id",property="id",jdbcType= JdbcType.VARCHAR,id=true),
            @Result(column="student_name",property="name",jdbcType=JdbcType.VARCHAR),
            @Result(column="student_sex",property="sex",jdbcType=JdbcType.TIMESTAMP)
    })
    Student selectById(Long id);

In the above example, the name of the student_name field in the query result set is inconsistent with the name attribute defined by the entity class Student, so Result is required for conversion; while the age name is consistent, so Result is not required for conversion.

Guess you like

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