Mybatis supplement - annotations, interceptors

Mybatis supplement - annotations, interceptors


Annotation is a new technology introduced from JDK 1.5.
Function of annotation:
It is not the procedure itself, which can be explained
Can be read by other programs
Annotation format
Annotation is implemented in the code in the form of @ annotation name, and some parameter values can be added
For example: @ SuppressWarnings(value = "unchecked")
Where notes are used:
package, class, method and field are equivalent to adding additional auxiliary information to them

Meta annotation:

@Target: used to describe the scope of use of annotations
@Retention: used to describe the lifecycle of annotations
@Documented: indicates that the annotation will be included in the javadoc
@Inherited: indicates that the subclass can inherit the annotation in the parent class
@Repeatable: repeatable annotation

Built in annotation

@Override: override check
@Deprecated: obsolete
@SuppressWarnings: suppress warnings
@Functional interface: functional interface

Custom annotation

public @interface MyAnno{}

MyBatis annotation

@Select("select * from user where uid=#{uid}")
    public User findUserById(int uid);

MyBatis common notes

@Insert: the sql syntax in the new implementation is exactly the same as that in xml
@Update: implement update
@Delete: implements deletion
@Select: implement query
@Result: implement result set encapsulation
@Results: can be used with @ Result to encapsulate multiple Result sets
@ResultMap: implements encapsulation defined by referencing @ Results
@One: implement one-to-one result set encapsulation
@Many: implement one to many result set encapsulation
@SelectProvider: implement dynamic SQL mapping
@ResultMap: reference result set
@SelectKey: get the latest insert

@Select @Results @Result

Note: Profile

Use annotations to implement mapping queries:

@Select("select * from user where uid=#{uid}")
@Results(id = "userMap",value= {
            @Result(id = true,column = "uid",property = "uid"),
            @Result(column = "uname",property = "uame"),
            @Result(column = "address",property = "address")
public User findUserById(Integer uid);


Use the annotation @ ResultMap to reuse the result map:

@Select("select * from user where uid=#{uid}")
@Results(id = "userMap",value= {
            @Result(id = true,column = "uid",property = "uid"),
            @Result(column = "uname",property = "uame"),
            @Result(column = "address",property = "address")
public User findUserById(Integer uid);
@ResultMap(value = "userMap")  
@Select("select * from user")
public List<User> findAllUser();

@Insert @SelectKey

Use the annotation @ SelectKey to obtain the auto growth primary key

     * Note: before=false
    @Insert("insert into user(uname,sex,address)values
    @SelectKey(before = false,keyColumn = "uid",
       keyProperty = "uid",
      statement = "select last_insert_id()",
      resultType = Integer.class)
    public int insertUser(User user);

@Delete @Param

Use the annotation @ Param to map parameters

     * Delete user based on primary key
     *  Note that #{userId} corresponds to @ Param("userId")

    @Delete("delete from user where uid=#{userId}")
    public void delete(@Param("userId") Integer uid);


 @Select("select * from user where uname like #{username} and sex=#{sex}")
 public List<User> findUserByNameAndSex(@Param("username") String uname, @Param("sex") String sex);


Use the annotation @ Update to complete the modification

     * Modify user information
@Update("update user set uname=#{uname},address=#{address} where uid=#{uid}")
public int updateUser(User user);

Association mapping: @ One

Complete One-to-One association mapping with annotation @ One (One order corresponds to One user):

	@Result(id=true,column = "oid",property = "oid"),
	@Result(column = "user_id",property = "userId"),
	@Result(column = "user_id",property = "user", one=@One(select = "com.wdzl.mybatis.mapper.ItemsMapper.findUserById"))
@Select("select orders.* from orders where oid=#{oid}")
public Order findOrderById(Integer oid);

Association mapping: @ Many

Use annotation @ Many to complete one to Many association mapping (one order corresponds to multiple order details)

	@Result(id=true,column = "oid",property = "oid"),
	@Result(column = "user_id",property = "userId"),
	@Result(column = "oid",property = "orderDetails",many=@Many(select = "com.wdzl.mybatis.mapper.ItemsMapper.findOrderDetails"))
@Select("select orders.* from orders where oid=#{oid}")
public Order findOrder(Integer oid);

Use annotation embedded Script script to realize dynamic SQL (understand)

    @Update("<script>update school " +
            "<set>" +
            "  <if test=\"schoolName!=null\">" +
            "       sCname=#{schoolName}," +
            "  </if>" +
            "  <if test=\"address!=null\">" +
            "       address=#{address}," +
            "  </if>" +
            "</set>" +
            "<where>" +
            " <if test=\"scid!=null\">" +
            "   scid=#{scid}" +
            " </if>" +
            "</where>" +
    public void update(School school);

Use Provider annotation identification


(1) Define first Provider class
   new SQL(){
                ORDER_BY("birthday desc");

(2) Annotation usage Provider class
    @SelectProvider(type = StudentProvider.class,method = "query")
    public List<Student> list(Student student);


Interceptor execution principle

Interceptor interfaceInterceptor implementation class

Executor: method to intercept the executor.
ParameterHandler: processing of intercepting parameters.
ResultHandler: intercepts the processing of the result set.
StatementHandler: intercepts Sql syntax build processing

Interceptors need to implement the org.apache.ibatis.plugin.Interceptor interface.

Interceptor - Custom interceptor steps

(1) Customize the interceptor class that implements the org.apache.ibatis.plugin.Interceptor interface, and implement the methods therein
(2) Add @ Intercepts annotation, write the object and method to be intercepted, and the method parameters.

(3) Add a plug-in configuration interceptor to the configuration file

Tags: Java

Posted on Sun, 28 Nov 2021 04:47:09 -0500 by the_924