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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章