Mybatis内嵌对象或者集合

 

1.嵌套集合、对象的类

public class SysUser implements Serializable {
    //普通String属性
    private String userId;
    private String userName;
    private String userPhone;
    private String userPassword;
    private String userLastLoginTime;
    private String userCreateTime;
    private String userStatus;
    //对象属性
    private UserRole userRole;
    //对象集合属性
    private List<Role> roles;

}

public class UserRole implements Serializable {
    private String userRoleId;
    private String userId;
    private String roleId;
    private String userRoleStatus;
}



public class Role implements Serializable {
    private String roleId;
    private String roleCode;
    private String roleName;
    private String roleDesc;
    private String roleStatus;
}

 

2.嵌套集合、对象的配置文件

<!--根据用户名查找用户-->
<select id="findByName" resultMap="SysUser">
    SELECT su.* ,ur.*,r.*
    FROM sys_user AS su LEFT JOIN user_role AS ur ON su.`user_id` = ur.`user_id`
                        LEFT JOIN role AS r ON ur.`role_id` = r.`role_id`
                        WHERE su.`user_phone` = #{username}
</select>


<resultMap id="SysUser" type="xyz.lande.demo.entity.SysUser">
    <id property="userId" column="user_id"></id>
    <result property="userName" column="user_name "></result>
    <result property="userPhone" column="user_phone"></result>
    <result property="userPassword" column="user_password"></result>
    <result property="userLastLoginTime" column="user_last_login_time"></result>
    <result property="userCreateTime" column="user_create_time"></result>
    <result property="userStatus" column="user_status"></result>
    <!--UserRole对象-->
    <association property="userRole" javaType="xyz.lande.demo.entity.UserRole">
        <id property="userRoleId" column="user_role_id"></id>
        <result property="userId" column="user_id"></result>
        <result property="roleId" column="role_id"></result>
        <result property="userRoleStatus" column="user_role_status"></result>
    </association>
    <!--Role对象List集合-->
    <collection property="roles" ofType="xyz.lande.demo.entity.Role">
        <id property="roleId" column="role_id"></id>
        <result property="roleCode" column="role_code"></result>
        <result property="roleName" column="role_name"></result>
        <result property="roleDesc" column="role_desc"></result>
        <result property="roleStatus" column="role_status"></result>
    </collection>
</resultMap>

 

3.注意:配置文件中,集合的字段跟父级字段相同,只返回一条集合数据。需要修改配置文件中集合的字段名称。

 

posted @ 2021-09-02 14:24  kerwin cui  阅读(1489)  评论(0编辑  收藏  举报