在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對象會被自動填充,從而實現多對一的關聯關系。