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{ /** * 根据名称查询用户 * @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"> <select id="selectByName" resultType="com.example.demo.model.User"> select * from `user` where `name` = #{name} select> mapper>
现在,我们可以解答它们的映射原理了:
- xml 文件关联 .java 文件是通过 xml 文件中
标签的 namespace 属性指定要映射文件所在的路径来讲两者关联起来的; - xml 文件中的 sql 通过 Mybatis 的语句标签,比如
这里需要注意的是:
- 接口中的方法参数想要传递给 xml 中,除非参数是唯一的,否则需要使用 @Param 来表名参数名称;
- xml 中使用接口方法参数的方式为 #{item} ,item 为参数名,可以多级使用,比如 item.user.name。
二、我的项目上实例:
@Mapper @Component public interface ConferenceDao extends MyBaseMapper{ /** * * @Title: queryConferenceList * @Description: 查询会议列表 * @param conferenceQueryListVo * @return 参数 * @return List 返回类型 * @throws */ ListqueryConferenceList(ConferenceQueryListVo conferenceQueryListVo); List getVipConfServiceList(@Param("roomIds")List roomIds,@Param("type") Integer type);
ListselectDeviceIdsByConfIds(@Param("confIds") List 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" />