Mybatis core annotation summary

Posted by iamchris on Wed, 24 Nov 2021 01:26:40 +0100

1, Foreword

This article mainly introduces some annotations encountered in using mybatis in the project. Although it is not the most complete, it is basically enough for development.

2, Mybatis annotation

1,@Results

Function: used to map query result set to entity class attribute. When the database field name is inconsistent with the attribute name corresponding to the entity class, you can use the @ Results mapping to correspond it. column is the database field name, porperty is the entity class attribute name, JDBC type is the database field data type, and id is whether it is the primary key.

Application code:

@Select({"select id, username, password from book"})
@Results({
    @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
    @Result(column="username", property="userName", jdbcType=JdbcType.VARCHAR),
    @Result(column="password ", property="passWord", jdbcType=JdbcType.VARCHAR)
})
List<Book> findAllBook();

Note: the mapping relationship between database field name username and entity class attribute name username is established in this way.

2, @Result

Function: @ Result commonly used properties are column and property, which are used to configure the mapping relationship between column names in the database and property names in the class.

Application code:

@Select({"select id, username, password from book"})
@Results(id="studentMap", value={
    @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
    @Result(column="username", property="userName", jdbcType=JdbcType.VARCHAR),
    @Result(column="password ", property="passWord", jdbcType=JdbcType.VARCHAR)
})
List<Book> findAllBook();

@Select({"select id, username, password from book where id = #{id}"})
@ResultMap(value="studentMap")
Book selectById(integer id);

3,@SelectKey

Function: the function of this annotation is completely consistent with the < SelectKey > tag. This annotation can only be used on the methods marked by @ Insert or @ InsertProvider or @ Update or @ UpdateProvider, otherwise it will be ignored. If the @ SelectKey annotation is marked, MyBatis will ignore the generated primary key or configuration attribute set by the @ Options annotation.

Application code:
This example shows how to use the @ SelectKey annotation to read the value of the database sequence before insertion:

keyProperty: Specifies the name of the corresponding property of the object passed in as a parameter, which will be updated to a new value,

Before: you can specify true or false to indicate whether the SQL statement should be executed before or after the insertion statement.

resultType: Specifies the Java type of keyProperty.

@Insert("insert into table3 (id, name) values(#{nameId}, #{name})")
@SelectKey(statement="call next value for TestSequence", keyProperty="nameId", before=true, resultType=int.class)
int insertTable3(Name name);

4,@MapperScan

Function: specify the package where the interface to become the implementation class is located, and then all interfaces under the package will generate corresponding implementation classes after compilation, which are added on the Springboot startup class.

Application code:

@SpringBootApplication
@MapperScan("com.winter.Book")
public class SpringbootMybatisDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
    }
}

5,@Result

Role: a single result mapping between a column and an attribute or field. Attributes: id, column, javaType, JDBC type, typeHandler, one, many. The id attribute is similar to the XML element < id >, which is a Boolean value indicating whether the attribute is used to uniquely identify and compare objects. The one attribute is an association, similar to < Association >, while the many attribute is a collection Association, similar to < Collection >. This naming is to avoid name conflicts.

Code application:

@Results(id = "userResult", value = {
  @Result(property = "id", column = "uid", id = true),
  @Result(property = "firstName", column = "first_name"),
  @Result(property = "lastName", column = "last_name")
})
@Select("select * from users where id = #{id}")
User getUserById(Integer id);

6,@Mapper

Function: after the @ mapper annotation is added, the interface will generate corresponding implementation classes during compilation. It is not necessary to set the scanning address in the spring configuration. The namespace attribute in mapper.xml corresponds to the relevant mapper classes. Spring will dynamically generate beans and inject them into ServiceImpl. It is generally used on the interface for querying data. The tag is a mapping interface.

Code application:

@Mapper 
public interface UserDAO {
    public User findAll(); //Where findAll is the id name of the data query statement in the xml file
}

7,@Param

Function: if your mapping method accepts multiple parameters, you can use this annotation to customize the name of each parameter. Otherwise, by default, parameters other than rowboundaries will be named with "param" plus parameter position. For example, #{param1}, #{param2}. If @ Param("person") is used, the parameter will be named #{person}.

Application code:

@Mapper 
public interface UserDAO {
     public int selectColumn(@Param("userid") int userid);
}

8,@Insert

9,@Update

10,@Delete

Note: 8, 9 and 10 are added, modified and deleted together.
Function: each annotation represents the SQL statement to be executed. They take an array of strings (or a single string) as arguments. If a string array is passed, the string array will be connected into a single complete string, with a space between each string. This effectively avoids the problem of "missing spaces" when building SQL statements with Java code. Of course, you can also manually connect strings in advance. Attribute: value, which specifies the array of strings used to form a single SQL statement.

Application code:

@Select("select * from user where id = #{id}")
User findById(@Param("id") long id);

11,@ResultMap

Function: this annotation specifies the id of the < ResultMap > element in the XML map for the @ select or @ SelectProvider annotation. This allows the annotated select to reuse the ResultMap that has been defined in XML. If there are @ Results or @ ConstructorArgs annotations in the select annotation of the annotation, these two annotations will be overwritten by this annotation.

Application code:

   @Results(id="userMap", value={
			@Result(column="id", property="id", id=true),
		    @Result(column="user_name", property="userName"),
		    @Result(column="user_password ", property="userPassword"),	  
	})
	@Select({"select * from sys_user"})
	@ResultMap("userMap")
	List<SysUser> selectUsers();

Remember to give me three company! If you have any questions, welcome to communicate with me. Or pay attention to my WeChat public official account for more study.

Topics: Java Mybatis Spring Boot