在进行表查询的时候如果需要将结果集封装为多个实体类对象,可以在xml中使用resultMap解决,但如果使用的是注解则需要使用@Result
以下是一对一两表查询的例子,需要对结果集的每一个column表字段都分别进行实体对象属性映射,比较笨重
@Select("select *, o.id oid from orders as o, user as u where u.id = o.uid")
@Results({
@Result(column = "oid", property = "id"),
@Result(column = "ordertime", property = "ordertime"),
@Result(column = "total", property = "total"),
@Result(column = "uid", property = "user.id"),
@Result(column = "username", property = "user.username"),
@Result(column = "password", property = "user.password")
})
List<Order> findAll();
所以现在将两表查询拆分成两个select语句,分别封装到不同接口抽象方法中,将@result与@One搭配使用,其中javaType指定@One查询语句返回的Java类、column是select * from orders返回的结果集字段之一,代表将该column字段传入到@One所对应的查询语句中的 #{id}、property指定返回的结果集最终封装成的属性(Order类)
@Select("select * from orders")
@Results({
@Result(id = true, column = "id", property = "id"),
@Result(column = "ordertime", property = "ordertime"),
@Result(column = "total", property = "total"),
@Result(
javaType = User.class,
column = "uid",
property = "user",
one = @One(select = "com.itheima.mapper.UserMapper.findById")
)
})
List<Order> findUserAndRoleAll();
@Select("select id, username, password from user where id = #{id}")
User findById(int id);
@Many与@One效果一致,为了提高代码的可读性,@One一般用于一对一查询而@Many用于一对多或者多对多查询