SpringBoot mybatis多對一查詢、多對多查詢


查詢用戶列表,並查詢每個用戶下面最新的一個訂單,和每個用戶下面的所有訂單。

package com.yutangzongcai.demo.mapper;

import com.yutangzongcai.demo.entity.DingdanEntity;
import com.yutangzongcai.demo.entity.UsersEntity;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UsersMapper {

    /**
     * 查詢用戶列表
     * 同時多對一 【查詢用戶最新1個訂單】
     * 同時多對多 【查詢用戶所有訂單】
     * @return
     */
    @Select("select id,name,age from users order by id asc")
    @Results(id = "empMap", value = {
            @Result(column = "id", property = "id", id = true),
            @Result(column = "name2", property = "name"),
            @Result(column = "id", property = "dingdanOne", one = @One(select = "com.yutangzongcai.demo.mapper.UsersMapper.dingdanOne")),
            @Result(column = "id", property = "dingdanMany", many = @Many(select = "com.yutangzongcai.demo.mapper.UsersMapper.dingdanMany"))
    })
    List<UsersEntity> all();

    /**
     * 查詢用戶最新1個訂單
     * @param userId
     * @return
     */
    @Select("select * from dingdan where userId=#{userId} order by id desc limit 0,1")
    DingdanEntity dingdanOne(@Param("userId") Integer userId);

    /**
     * 查詢用戶所有訂單(按最新排序)
     * @param userId
     * @return
     */
    @Select("select * from dingdan where userId=#{userId} order by id desc")
    List<DingdanEntity> dingdanMany(@Param("userId") Integer userId);

}

在使用@Result注解進行one對一關聯或many對多關聯時,必須設置主鍵,只有設置了主鍵,才能通過主鍵傳入參數,進行子查詢。

關聯查詢時,被關聯的方法入參userId,是由@Result設置中的主鍵所決定的,這里mybatis已經進行了自動傳入。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM