在Mybatis中,实现多对一的关联查询通常需要使用ResultMap来映射多表的数据,具体步骤如下:
<select id="selectUserAndRole" resultMap="userAndRoleMap">
select u.id as userId, u.username, r.id as roleId, r.roleName
from user u
left join role r on u.roleId = r.id
</select>
<resultMap id="userAndRoleMap" type="User">
<id property="id" column="userId"/>
<result property="username" column="username"/>
<association property="role" columnPrefix="role_">
<id property="id" column="roleId"/>
<result property="roleName" column="roleName"/>
</association>
</resultMap>
public class User {
private Long id;
private String username;
private Role role;
// getter and setter methods
}
public class Role {
private Long id;
private String roleName;
// getter and setter methods
}
User user = userMapper.selectUserAndRole();
通过以上步骤,就可以实现多对一的关联查询操作。在查询结果中,User对象中的Role对象会被自动填充,从而实现多对一的关联关系。