CRUD操作:@Insert,@Update,@Delete,@Select
@Result:实现结果集封装
@Results:可以与@Result一起使用,封装结果集
@ResultMap:实现引用@Results定义的封装
@One:实现一对一结果集封装 @Many:实现一对多结果集封装
@SelectProvider:实现动态SQL映射
@CacheNamespace:实现注解二级缓存的使用
当实体类的属性与数据库表的列名不一致:
public Interface UserDao{
@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();
@Select("select * from user where id=#{uid}")
@ResultMap("userMap")
User findById(Integer userId);
}
@Results注解代替的是标签resultMap,该注解中可以使用单个@Result注解,也可以使用@Result集合
@Result注解代替了标签id和标签result,其中属性介绍:id是否是主键字段;column是数据库表的列名;property是需要装配的属性名
@One(一对一):代替了标签assocation,是多表查询的关键,在注解中用来指定子查询返回单一对象
@Many(多对一):代替了标签collection,是多表查询的关键,在注解中用来指定子查询返回对象集合
/**AccountDao(一对一)**/
@Select("select * from account")
@Results(id="accountMap",value={
@Result(id=true,column="id",property="id"),
@Result(column="money",property="money"),
......
@Result(column="uid",property="user",one=@One(select="com.it.dao.UserDao.findById",fetchType=FetchType.LAZY))
})
List<Account> findAll();
/**UserDao(多对一)**/
@Select("select * from user")
@Results(id="userMap",value={
@Result(id=true,column="id",property="id"),
.......
@Result(column="id",property="accountList",many=@Many(select="com.it.dao.AccountDao.findByUid",fetchType=FetchType.LAZY))
})
List<User> findAll();
基于注解的二级缓存开发:
/**MyBatis-Config.xml**/
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
@CacheNamespace(blocking=true)
public interface UserDao{
}