这几年来注解开发越来越流行,Mybatis也可以使用注解开发方式,这样我们就可以减少编写Mapper映射文件了。我们先围绕一些基本的CRUD来学习,再学习复杂映射多表操作。
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@CacheNamespace(blocking = true)
修改MyBatis的核心配置文件,我们使用了注解替代的映射文件,所以我们只需要加载使用了注解的Mapper接口即可
<mappers>
<mapper class="com.itheima.mapper.UserMapper">mapper>
mappers>
或者指定扫描包含映射关系的接口所在的包也可以
<mappers>
<package name="com.itheima.mapper">package>
mappers>
实现复杂关系映射之前我们可以在映射文件中通过配置来实现,使用注解开发后,我们可以使用@Results注解
,@Result注解,@One注解,@Many注解组合完成复杂关系的配置
@Results
代替的是标签该注解中可以使用单个@Result注解,也可以使用@Result集
合。使用格式:@Results({@Result(),@Result()})或@Results(@Result())
@Resut
代替了标签和标签
@Result中属性介绍:
column:数据库的列名
property:需要装配的属性名
one:需要使用的@One 注解(@Result(one=@One)()))
many:需要使用的@Many 注解(@Result(many=@many)()))
@One (一对一)
代替了 标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
@One注解属性介绍:
select: 指定用来多表查询的 sqlmapper
使用格式:@Result(column=" ",property="",one=@One(select=""))
@Many (多对一)
代替了标签, 是是多表查询的关键,在注解中用来指定子查询返回对象集合。
使用格式:@Result(property="",column="",many=@Many(select=""))
@CacheNamespace(blocking = true)
在需要开启的接口中加入
mybatis 基于注解方式实现配置二级缓存
一对一模型 在前面mybatis的封装结果集中有这一对一
public interface OrderMapper {
@Select("select * from orders")
@Results({
@Result(id=true,property = "id",column = "id"),
@Result(property = "ordertime",column = "ordertime"),
@Result(property = "total",column = "total"),
@Result(property = "user",column = "uid",
javaType = User.class,
one = @One(select =
"com.itheima.mapper.UserMapper.findById"))
})
List<Order> findAll();
}
public interface UserMapper {
@Select("select * from user where id=#{id}")
User findById(int id);
}
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(id = true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "password",column = "password"),
@Result(property = "birthday",column = "birthday"),
@Result(property = "orderList",column = "id",
javaType = List.class,
many = @Many(select =
"com.itheima.mapper.OrderMapper.findByUid"))
})
List findAllUserAndOrder();
}
public interface OrderMapper {
@Select("select * from orders where uid=#{uid}")
List findByUid(int uid);
}
public interface UserMapper {
@Select("select * from user")
@Results({
@Result(id = true,property = "id",column = "id"),
@Result(property = "username",column = "username"),
@Result(property = "password",column = "password"),
@Result(property = "birthday",column = "birthday"),
@Result(property = "roleList",column = "id",
javaType = List.class,
many = @Many(select =
"com.itheima.mapper.RoleMapper.findByUid"))
})
List<User> findAllUserAndRole();
}
public interface RoleMapper {
@Select("select * from role r,user_role ur where r.id=ur.role_id and ur.user_id=#{uid}")
List<Role> findByUid(int uid);
}