mybatis三(关联查询)

Posted on 2019-01-16 23:40  FLGB  阅读(203)  评论(0编辑  收藏  举报

一、类属性

@Alias("depart")
public class Department {

private Integer id;
private String departName;
private List<User> users;

 

@Alias("user")
public class User {

private int id;
private String lastName;
private String email;
private String gender;
private Department dept;

二、定义方法

public User selectUserByIdStep(Integer id);

三、mapper配置

<resultMap type="depart" id="dMap">
        <id column="depart_id" property="id" />
        <result column="depart_name" property="departName"/>
        <!-- collection的属性封装 -->
        <collection property="users" ofType="user">
            <id column="id" property="id" />
            <result column="last_name" property="lastName"/>
            <result column="email" property="email"/>
            <result column="gender" property="gender"/>
        </collection>
    </resultMap>
    <select id="selectDepartAndUser" resultMap="dMap">
        SELECT
        u.id,u.depart_id,u.email,u.gender,u.last_name,d.depart_name FROM USER
        u LEFT JOIN department d ON u.depart_id=d.id WHERE d.id=#{id}
    </select>

2. <!-- 鉴别器 

<discriminator javaType="">
可以根据某列的值改变封装行为
如果查询出是女生,则把部门查询出来
如果是男生,把list_name这列赋值给email
-->

<select id="selectUserDis" resultMap="disMap">
        SELECT * FROM USER WHERE id =#{id}
    </select>
    <!-- 鉴别器 
        <discriminator javaType="">
         可以根据某列的值改变封装行为
         如果查询出是女生,则把部门查询出来
         如果是男生,把list_name这列赋值给email
    -->
    <resultMap type="user" id="disMap">
        <id column="id" property="id"/>
        <result column="email" property="email"/>
        <result column="last_name" property="lastName"/>
        <result column="gender" property="gender"/>
        <discriminator javaType="string" column="gender">
            <!-- 女生 -->
            <case value="0" resultType="user">
                <association property="dept" select="mapper.DepartMapper.selectDepartById" column="{id=depart_id}" fetchType="eager">
                </association>
            </case>
            <!-- 男生 -->
            <case value="1" resultType="user">
                <id column="id" property="id"/>
                <result column="last_name" property="email"/>
                <result column="last_name" property="lastName"/>
                <result column="gender" property="gender"/> 
            </case>
        </discriminator>
    </resultMap>

 

Copyright © 2024 FLGB
Powered by .NET 8.0 on Kubernetes