mybatis one-to-many mapping processing

One-to-many: The company corresponds to multiple employees, so it should be a company object, and there is an attribute in it that is multiple employee objects, whether it is a list or a map, the following company class and employee class

@Data
public class Com {
    public  int comId;
    public  String comName;
    public List<Worker> workers;
}
@Data
public class Worker {
    public String workerName;
    public int WorkerId;
    public  int comId;
}

Processing method 1: collection

The joint query of the company table and the personnel table is like this,

select * from fix inner  join fix_pic where fix.fix_id =fix_pic.fix_id;

turn out

 We need to put these results into a company object. There is a list attribute in the company object, which stores worker information in turn.

So we need to use the collectorction

   <!--      id  被调用时的名字   type   对应的实体类-->
    <resultMap id="querycom" type="com">
        <!--  com实体类的属性   ,对应的数据库中的字段名      -->
        <result property="comId" column="com_id"></result>
        <result property="comName" column="com_name"></result>
        <!--   property实体类的属性  ofType内层类-->
        <collection property="workers" ofType="worker" javaType="list">
            <result property="workerName" column="worker_name"></result>
            <result property="workerId" column="worker_id"></result>
        </collection>
    </resultMap>

    <select id="query" resultMap="querycom">
        select *
        from com
                 inner join worker
        where worker.com_id = com.com_id
    </select>

If you only need a certain attribute of the student class, then ofType="string" is enough.

Processing method 2: assosation multi-table joint query

Because it is a joint query of the employee table and the company table, the company id is associated, so after I find a company id, I go to the employee table to check the company id, and put the query results of the employee table into the attributes of the company class.

<!--      id  被调用时的名字   type   对应的实体类-->
    <resultMap id="commap" type="com">
        <!--  com实体类的属性   ,对应的数据库中的字段名      -->
        <result property="comId" column="com_id"></result>
        <result property="comName" column="com_name"></result>
        <!--   property  com实体类的属性  select第二步要执行的查询语句的id  cloumn 给第二步传的值-->
        <association property="workers" select="queryworkers" column="com_id"></association>
    </resultMap>
<!--   第一步查询  ,需要mapper调用-->
    <select id="qerucom" resultMap="commap">
        select *
        from com
    </select>
<!--    第二步查询 ,程序自己调用-->
     <select id="queryworkers"  resultType="worker" parameterType="string">
        select * from worker where com_id=#{com_id}
     </select>

 

Guess you like

Origin blog.csdn.net/sharesb/article/details/127932028