Annotation development of Mybatis_day4_Mybatis

  • Annotation development has become more and more popular in recent years, and Mybatis can also use annotation development, so that we can reduce the writing of Mapper mapping files.

Mybatis common notes

  • @Insert: Implement new
  • @Update: Implement update
  • @Delete: Implement delete
  • @Select: Implement query
  • @Result: Implement result set encapsulation
  • @Results: Can be used with @Result to encapsulate multiple result sets
  • @ResultMap: Implement the encapsulation defined by reference @Results
  • @One: Implement one-to-one result set encapsulation
  • @Many: Implement one-to-many result set encapsulation
  • @SelectProvider: Implement dynamic SQL mapping
  • @CacheNamespace: Implement the use of annotated secondary cache

Use Mybatis annotations to implement basic CRUD

  1. Write entity class
public class User implements Serializable {
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;

public Integer getUserId() {
	return userId;
}
public void setUserId(Integer userId) {
	this.userId = userId;
}
.....
  • Note: The attribute name of User here is not consistent with the column name of the database table.

  1. Use annotations to develop the persistence layer interface
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id="userMap",
	value= {
		@Result(id=true,column="id",property="userId"),
		@Result(column="username",property="userName"),
		@Result(column="sex",property="userSex"),
		@Result(column="address",property="userAddress"),
		@Result(column="birthday",property="userBirthday")
		}
		)
List<User> findAll();


/**
* 根据 id 查询一个用户
* @param userId
* @return
*/
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);


/**
* 保存操作
* @param user
* @return
*/
@Insert("insert into user(username,sex,birthday,address)values(#{username},#{sex},#{birthday},#{address})")
int saveUser(User user);


/**
* 更新操作
* @param user
* @return
*/
@Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id =#{id} ")
int updateUser(User user);


/**
* 删除用户
* @param userId
* @return
*/
@Delete("delete from user where id = #{uid} ")
int deleteUser(Integer userId);


/**
* 查询使用聚合函数
* @return
*/
@Select("select count(*) from user ")
int findTotal();

/**
* 模糊查询
* @param name
* @return
*/
@Select("select * from user where username like #{username} ")
List<User> findByName(String name);
}

  1. Write SqlMapConfig configuration file

<!-- 配置映射信息 -->
<mappers>
	<!-- 配置 dao 接口的位置,它有两种方式
第一种:使用 mapper 标签配置 class 属性
第二种:使用 package 标签,直接指定 dao 接口所在的包
-->
	<package name="cn.myp666.dao"/>
</mappers>



Using annotations to implement complex relationship mapping development

  • Before implementing complex relationship mapping, we can <resultMap>achieve it through configuration in the mapping file. When developing with annotations, we need to use @Results annotation, @Result annotation, @One annotation, @Many annotation.

Annotation explanation of complex relationship mapping
  • @Results 注解

    • Instead of labels<resultMap>
    • You can use a single @Result annotation in this annotation, or you can use the @Result collection
      • @Results({@Result(),@Result()})或@Results(@Result())
  • @Result 注解

    • Replace <id>tags and <result>tags
    • Introduction to attributes in @Result:
      • id is the primary key field
      • column The column name of the database
      • property The name of the property to be assembled
      • one @One annotation to be used (@Result (one = @ One) ()))
      • Many @Many annotations to be used (@Result (many = @ many) ()))
  • @One注解(One to one)

    • Instead of <assocation>labels, it is the key to multi-table queries and is used in annotations to specify that subqueries return a single object.
    • @One annotation attribute introduction:
      • select specifies the sqlmapper used for multi-table queries
      • fetchType will override global configuration parameters
      • lazyLoadingEnabled。。
    • Use format:
      • @Result(column=" “,property=” “,one=@One(select=” "))
  • @Many注解(Many to one)

    • Instead of <Collection>labels, it is the key to multi-table queries and is used in annotations to specify that the subquery returns a collection of objects.
    • Note: Aggregate elements are used to handle the "one-to-many" relationship. You need to specify the attribute of the mapped Java entity class, the javaType of the attribute (generally ArrayList), but it can not be defined in the annotation;
    • Use format:
      • @Result(property=" “,column=” “,many=@Many(select=” "))

One-to-many complex relationship mapping using annotations
  1. Add the account's persistence layer interface and use annotation configuration
public interface IAccountDao {
/**
* 查询所有账户,采用延迟加载的方式查询账户的所属用户
* @return
*/
@Select("select * from account")
@Results(id="accountMap",
	value= {
		@Result(id=true,column="id",property="id"),
		@Result(column="uid",property="uid"),
		@Result(column="money",property="money"),
		@Result(column="uid",
				property="user",
				one=@One(select="cn.myp666.dao.IUserDao.findById",fetchType=FetchType.LAZY)
)
})
List<Account> findAll();
}

  1. Add user's persistence layer interface and use annotation configuration
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id="userMap",
	value= {
		@Result(id=true,column="id",property="userId"),
		@Result(column="username",property="userName"),
		@Result(column="sex",property="userSex"),
		@Result(column="address",property="userAddress"),
		@Result(column="birthday",property="userBirthday")
})
List<User> findAll();


/**
* 根据 id 查询一个用户
* @param userId
* @return
*/
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);
}


One-to-many complex relationship mapping using annotations
  1. Write user persistence layer interface and use annotation configuration
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id="userMap",
	value= {
		@Result(id=true,column="id",property="userId"),
		@Result(column="username",property="userName"),
		@Result(column="sex",property="userSex"),
		@Result(column="address",property="userAddress"),
		@Result(column="birthday",property="userBirthday"),
		@Result(column="id",
				property="accounts",
				many=@Many(select="cn.myp666.dao.IAccountDao.findByUid",
				fetchType=FetchType.LAZY)
				)
			}
		)
	List<User> findAll();
}
  • @Many:Equivalent <collection>configuration
  • select attribute: represents the sql statement to be executed
  • fetchType attribute: represents the loading method, generally set to LAZYthe value if you want to delay loading

  1. Write the account's persistence layer interface and use annotation configuration
public interface IAccountDao {
/**
* 根据用户 id 查询用户下的所有账户
* * @param userId
* @return
*/
@Select("select * from account where uid = #{uid} ")
List<Account> findByUid(Integer userId);
}



mybatis annotated secondary cache

  1. Enable secondary cache support in SqlMapConfig
<!-- 配置二级缓存 -->
<settings>
<!-- 开启二级缓存的支持 -->
	<setting name="cacheEnabled" value="true"/>
</settings>
  1. Use annotations to configure the second-level cache in the persistence layer interface
@CacheNamespace(blocking=true)//mybatis 基于注解方式实现配置二级缓存
public interface IUserDao {}
Published 94 original articles · praised 0 · visits 2097

Guess you like

Origin blog.csdn.net/qq_16836791/article/details/104802600