结果映射:
可以将查询结果通过别名或者是@Results注解与JavaBean属性映射起来。
使用@Results注解将指定列于指定JavaBean属性映射起来,执行SELECT查询,如:
public interface UserMapper{
@Select("SELECT * FROM USERS")
@Results(
{
@Result(id = true, column = "user_id", property = "userId"),
@Result(column = "name", property = "name"),
@Result(column = "email", property = "email"),
@Result(column = "password", property = "password")
})
List<User> findAllUsers();
}
注:
@Results 注解和映射器 XML 配置文件元素<resultMap>想对应。然而, MyBatis3.2.2 不能为@Results 注解赋予一个 ID。所以,不像<resultMap>元 素,我们不能在不同的映射语句中重用@Results 声明。这意味着即使@Results 注解完全相同,我们也需要(在不同的映射接口中)重复@Results 声明。
1.一对一映射:
mybatis提供了@One注解来使用嵌套select 语句(Nested-Select)加载一对一关联查询数据。
用户与角色的关系,假设一个用户一个角色(与实际项目上不同,纯举例说明一对一映射关系)
public interface UserMapper
{
@Select("SELECT * FROM ROLES WHERE ROLE_ID=#{id}")
Role findRoleById(int id);
@Select("SELECT * FROM USERS WHERE USER_ID=#{userId} ")
@Results(
{
@Result(id = true, column = "user_id", property = "userId"),
@Result(column = "name", property = "name"),
@Result(column="password",property="password"),
@Result(column = "email", property = "email"),
@Result(property = "role", column = "role_id",
one = @One(select = "com.xhm.mappers.UserMapper.
findRoleById"))
})
User selectUserWithRole(int userId);
}
这里使用了@One 注解的 select 属性来指定一个使用了完全限定名的方法上,该方法会返回一个 Role对 象。使用 column=”role_id”,则 USERS表中列
role_id 的值将会作为输入参数传递给 findRoleById()方法。 如果@One SELECT 查询返回了多行结果,则会抛出 TooManyResultsException 异常
2.一对多映射
MyBatis 提供了@Many 注解,用来使用嵌套 Select 语句加载一对多关联查询。
用户与角色的关系,假设一个用户多个角色(与实际项目上不同,纯举例说明一对多映射关系)
public interface UserMapper
{
@Select("select * from roles where user_id=#{userId}")
@Results(
{
@Result(id = true, column = "role_id", property = "roleId"),
@Result(column = "rolename", property = "rolename"),
@Result(column = "privilege", property = "privilege_id"),
@Result(column = "description" property = "description")
})
List<Role> findRoleByUserId(int userId);
@Select("SELECT * FROM USERS where user_id=#{userId}")
@Results(
{
@Result(id = true, column = "user_id", property = "userId"),
@Result(column = "name", property = "name"),
@Result(column = "email", property = "email"),
@Result(property = "roles", column = "user_id",
many = @Many(select = "com.xhm.mappers.UserMapper.
findRoleByUserId"))
})
User findUserById(int tutorId);
}