1. 程式人生 > 其它 >mybatis/mybatis-plus 自定義SQL(多表查詢)

mybatis/mybatis-plus 自定義SQL(多表查詢)

轉:https://blog.csdn.net/aiwangtingyun/article/details/120225563

一、Mapper.java 和 Mapper.xml 對映關係
Mybatis 為我們提供了基本的增刪改查的介面,特別是 Mybatis-Plus 提供的 Wrappers 更是可以組合出更復雜的查詢語句以滿足我們需求。但有些複雜的操作,比如聯表查詢等,這些就需要使用自定義 SQL 語句進行操作的。

而編寫自定義 SQL 的操作為:

  • 在 Java 包下建立 xxxMapper.java 介面類,然後再 resources 資源包下建立對應的 xxxMapper.xml 檔案;
  • 建立好 .java 和 .xml 檔案後,在 Java 檔案編寫介面方法,然後再 xml 檔案中編寫對應方法的 SQL 語句;
  • 當呼叫介面中方法後,Mybatis 就會去 xml 檔案中找到對應的 SQL。

那麼,現在的問題是:Mybatis 是如何將介面中的方法與 xml 檔案中的 SQL 關聯起來的呢?

下面我們以一個具體例項進行講解,下面是介面檔案內容:

package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.model.User;
import org.apache.ibatis.annotations.Param;

public interface
UserMapper extends BaseMapper<User> { /** * 根據名稱查詢使用者 * @param name 使用者名稱 * @return 使用者實體 */ User selectByName(@Param("name") String name); }

然後在 resource 下建立對應的 xml 檔案:

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" 
> <mapper namespace="com.example.demo.mapper.UserMapper"> <!-- selectByName --> <select id="selectByName" resultType="com.example.demo.model.User"> select * from `user` where `name` = #{name} </select> </mapper>

現在,我們可以解答它們的對映原理了:

  • xml 檔案關聯 .java 檔案是通過 xml 檔案中 <mapper> 標籤的 namespace 屬性指定要對映檔案所在的路徑來講兩者關聯起來的;
  • xml 檔案中的 sql 通過 Mybatis 的語句標籤,比如 <select> 標籤中的 id 屬性指定介面中的方法名稱進行對映的。在這裡,id="selectByName" 表示該 SQL 語句標籤和介面中的 selectByName 方法進行關聯。

這裡需要注意的是:

  • 介面中的方法引數想要傳遞給 xml 中,除非引數是唯一的,否則需要使用 @Param 來表名引數名稱;
  • xml 中使用介面方法引數的方式為 #{item} ,item 為引數名,可以多級使用,比如 item.user.name。

 

二、我的專案上例項:

@Mapper
@Component
public interface ConferenceDao extends MyBaseMapper<Conference> {
    /**
     *
     * @Title: queryConferenceList
     * @Description: 查詢會議列表
     * @param conferenceQueryListVo
     * @return 引數
     * @return List<ConferenceListVo> 返回型別
     * @throws
     */
    List<ConferenceListVo> queryConferenceList(ConferenceQueryListVo conferenceQueryListVo);
    List<ConfServiceList>  getVipConfServiceList(@Param("roomIds")List<Integer> roomIds,@Param("type") Integer type);
   List<Integer> selectDeviceIdsByConfIds(@Param("confIds") List<Integer> confIds);
    Integer getCompleteConfServiceSum();
…… }

ConferenceMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zst.aim.dao.conference.ConferenceDao">
    <resultMap type="com.zst.aim.model.conference.vo.ConferenceListVo" id="queryListMap">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="status" property="status" />
        <result column="type" property="type" />
        <result column="startTime" property="startTime" />
        <result column="endTime" property="endTime" />
        <result column="gmt_create" property="gmtCreate" />
        <result column="display_name" property="createUserName" />
        <result column="phone_number" property="createUserPhoneNumber" />
        <result column="isSeatLayout" property="isSeatLayout" />
    <!--一對多查詢->
<collection property="rooms" ofType="com.zst.aim.model.conference.vo.RoomNameAndId" select="findRoomNameAndId" column="{conf_id = id}"> </collection> </resultMap> <select id="queryConferenceList" resultMap="queryListMap" parameterType="com.zst.aim.model.conference.vo.ConferenceQueryListVo"> SELECT a.id, a.`name`, a.`status` , a.`type` type, a.end_time endTime, a.start_time startTime, a.gmt_create, d.display_name, d.phone_number, IF(e.is_seat_layout=1, 1,0) isSeatLayout FROM conference a LEFT JOIN sys_user_info d on a.create_by = d.id LEFT JOIN nps_conference e on a.id = e.conf_id WHERE a.is_deleted = 0 and a.is_show = 1 and is_template = #{isTemplate} <if test = "name !=null and name !=''" > AND a.`name` LIKE CONCAT('%',#{name},'%') </if> <if test = "status!=null and status >= 0" > AND a.`status` = #{status} </if> <if test = "type!=null and type > 0" > AND a.`type` = #{type} </if> order by a.id desc </select> <select id="findRoomNameAndId" resultType="com.zst.aim.model.conference.vo.RoomNameAndId"> SELECT a.id as roomId,a.`name` as roomName FROM nps_room as a LEFT JOIN conference_equ as b on a.id = b.room_id WHERE b.conf_id = #{conf_id} </select> <select id="getVipConfServiceList" resultType="com.zst.aim.model.confService.ConfServiceList" parameterType="integer"> SELECT s.id, s.request_content, s.request_time, s.complete_time, s.state, s.room_id, i.display_name userName, i.phone_number, r.`name` roomName, c.`name` confName, c.start_time confStartTime, c.end_time confEndTime FROM nps_conf_service s LEFT JOIN sys_user_organization o ON o.id=s.request_user_id LEFT JOIN sys_user_info i ON i.id = o.user_id LEFT JOIN conference c ON c.id = s.request_conf_id LEFT JOIN conference_equ e ON c.id = e.conf_id LEFT JOIN nps_room r ON r.id = e.room_id WHERE <if test="type == 0"> s.state=0 </if> <if test="type == 1"> s.state=1 </if> <if test="null != roomIds and roomIds.size > 0"> and s.room_id in <foreach collection="roomIds" item="vipRoomId" open="(" separator="," close=")"> #{vipRoomId} </foreach> </if> <if test="null == roomIds or roomIds.size == 0"> and s.room_id is not null </if> ORDER BY s.request_time DESC </select>

   <select id="selectDeviceIdsByConfIds" resultType="java.lang.Integer">
SELECT a.device_id FROM nps_device_room as a
LEFT JOIN conference_equ as b ON b.room_id = a.room_id
WHERE b.conf_id in
<foreach collection="confIds" item="confId" open="(" close=")" separator=",">
#{confId}
</foreach>
</select>

    <select id="getCompleteConfServiceSum" resultType="integer">
select count(0) from nps_conf_service where date_format(complete_time,'%Y-%m')=date_format(now(),'%Y-%m')
</select>

…… </mapper>