Mybatis

Mybatis简介

  • MyBatis是一个优秀的基于ORM半自动轻量级持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码
  • MyBatis 本是apache的一个开源项目iBatis, 2010年6月这个项目由apache software foundation 迁移到了google code,随着开发团队转投到Google Code旗下,iBatis正式改名为MyBatis ,代码于2013年11月迁移到Github
  • Github地址:https://github.com/mybatis/mybatis-3/
  • MyBatis官网地址:http://www.mybatis.org/mybatis-3/

ORM思想

  • ORM(Object Relational Mapping)对象关系映射
  • O(对象模型):实体对象,即我们在程序中根据数据库表结构建立的一个个实体javaBean
  • R(关系型数据库的数据结构):关系数据库领域的Relational(建立的数据库表)
  • M(映射):从R(数据库)到O(对象模型)的映射,可通过XML文件映射
    在这里插入图片描述
  • mybatis采用ORM思想解决了实体和数据库映射的问题,对jdbc 进行了封装,屏蔽了jdbc api 底层访问细节,使我们不用与jdbc api 打交道,就可以完成对数据库的持久化操作

快速入门

案例需求:通过mybatis查询数据库user表的所有记录,封装到User对象中,打印到控制台上

  1. 创建数据库及user表; 创建maven工程,导入依赖(MySQL驱动、mybatis、junit)
  2. 编写jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis_db?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
  1. 编写User实体类
  2. 编写UserMapper.xml映射配置文件(ORM思想)
<?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">
<!--namespace:命名空间,与id属性共同构成唯一标识-->
<mapper namespace="userMapper">
    <!--resultType:返回结果类型(自动映射封装):要封装实体的全路径,起别名直接用别名-->
    <select id="findAll" resultType="user">
        select * from user
    </select>

    <!--parameterType代表参数类型 #{}代表占位符,占位符里面的内容代表parameterType参数中的各种成员变量且名字要一样-->
    <insert id="insertUser" parameterType="user">
        insert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})
    </insert>

    <update id="updateUser" parameterType="user">
        update user set username = #{username}, birthday = #{birthday}, sex = #{sex}, address = #{address} where id = #{id}
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>
</mapper>
  1. 编写SqlMapConfig.xml核心配置文件
    数据库环境配置
    映射关系配置的引入(引入映射配置文件的路径)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!--加载外部的properties文件-->
    <properties resource="./jdbc.properties"></properties>

    <!--起别名-->
    <typeAliases>
        <!--单个实体类起别名-->
        <!--<typeAlias type="com.lagou.bean.User" alias="user"></typeAlias>-->
        <!--批量起别名,别名就是指定包下的类名,不区分大小写-->
        <package name="com.lagou.bean"/>
    </typeAliases>

    <!--坏境配置,默认使用开发环境-->
    <environments default="develop">
        <!--开发环境-->
        <environment id="develop">
            <!--使用JDBC类型事务管理器-->
            <transactionManager type="JDBC"></transactionManager>
            <!--使用连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--加载映射配置-->
    <mappers>
        <mapper resource="./mapper/UserMapper.xml"></mapper>
    </mappers>
</configuration>
  1. 编写测试代码
public class MybatisTest {
    @Test
    public void testSelect() throws IOException {
        //1.加载核心配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        //2.获取sqlSessionFactory工厂对象
        SqlSessionFactory sqlSessionFactoryBuild = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //3.获取sqlSession会话对象,可以传一个boolean值,如果为true则自动开启事务,不需要手动提交,默认为false
        SqlSession sqlSession = sqlSessionFactoryBuild.openSession();
        //4.执行sql
        List<User> userList = sqlSession.selectList("userMapper.findAll");
        for (User user : userList) {
            System.out.println(user);
        }
        //5.释放资源
        sqlSession.close();
    }

    @Test
    public void testInsert() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession();
        User user = new User();
        user.setUsername("jack");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddress("北京海淀");
        sqlSession.insert("userMapper.insertUser", user);
        //手动提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void testUpdate() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession();
        User user = new User();
        user.setId(3);
        user.setUsername("tom");
        user.setBirthday(new Date());
        user.setSex("男");
        user.setAddress("北京朝阳");
        sqlSession.update("userMapper.updateUser", user);
        //手动提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void testdelete() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession();
        sqlSession.update("userMapper.deleteUser", 3);
        //手动提交事务
        sqlSession.commit();
        sqlSession.close();
    }
}

Mybatis映射文件概述

在这里插入图片描述

Mybatis核心文件概述

配置文档的顶层结构如下:
在这里插入图片描述

MyBatis常用配置解析

environments标签

数据库环境的配置,支持多环境配置
在这里插入图片描述

  1. 事务管理器(transactionManager)类型有两种:
  • JDBC:这个配置就是直接使用了JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务用域。
  • MANAGED:这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个命周期。 例如:mybatis与spring整合后,事务交给spring容器管理。
  1. 数据源(dataSource)常用类型有三种:
  • UNPOOLED:这个数据源的实现只是每次被请求时打开和关闭连接。
  • POOLED:这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来。
  • JNDI :这个数据源实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配数据 源,然后放置一个 JNDI 上下文的数据源引用

properties标签

实际开发中,习惯将数据源的配置信息单独抽取成一个properties文件,该标签可以加载额外配置的properties
在这里插入图片描述

typeAliases标签

类型别名是为 Java 类型设置一个短的名字。
为了简化映射文件 Java 类型设置,mybatis框架为我们设置好的一些常用的类型的别名
在这里插入图片描述

mappers标签

该标签的作用是加载映射的,加载方式有如下几种:

  1. 使用相对于类路径的资源引用,例如:
<mapper resource="org/mybatis/builder/userMapper.xml"/>
  1. 使用完全限定资源定位符(URL),例如:
file:///是文件协议,后面加上文件的绝对路径
<mapper url="file:///var/mappers/userMapper.xml"/>

下面两条是使用动态代理时使用的:

  1. 使用映射器接口实现类的完全限定类名,例如:
<mapper class="org.mybatis.builder.userMapper"/>
  1. 将包内的映射器接口实现全部注册为映射器,例如:
<package name="org.mybatis.builder"/>

Mybatis基本原理

在这里插入图片描述

代理开发方式

采用 Mybatis 的基于接口代理方式实现 持久层 的开发,这种方式是我们后面进入企业的主流。
基于接口代理方式的开发只需要程序员编写 Mapper 接口,Mybatis 框架会为我们动态生成实现类的对
象。
这种开发方式要求我们遵循一定的规范
在这里插入图片描述

  • Mapper.xml映射文件中的namespace与mapper接口的全包名相同
  • Mapper接口方法名和Mapper.xml映射文件中定义的每个statement的id相同
  • Mapper接口方法的输入参数类型和mapper.xml映射文件中定义的每个sql的parameterType的类型相同
  • Mapper接口方法的输出参数类型和mapper.xml映射文件中定义的每个sql的resultType的类型相同
//mapper实际上就是一个proxy代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.findById(1);

Mybatis基于接口代理方式的内部执行原理

  1. 通过追踪源码我们会发现,使用的mapper实际上是一个代理对象,是由MapperProxy代理产生的。
    在这里插入图片描述
  2. 追踪MapperProxy的invoke方法会发现,其最终调用了mapperMethod.execute(sqlSession, args)
    在这里插入图片描述
  3. 进入execute方法会发现,最终工作的还是sqlSession
    在这里插入图片描述

Mybatis高级查询

ResutlMap属性

  • resultType:如果实体的属性名与表中字段名一致,将查询结果自动封装到实体类中
  • resutlMap:如果实体的属性名与表中字段名不一致,可以使用ResutlMap实现手动封装到实体中
<?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.lagou.mapper.UserMapper">
    <!--id:此标签唯一标识; type:封装后的实体类型-->
    <resultMap id="userResultMap" type="user">
        <!--表中主键字段封装-->
        <id property="id" column="id"></id>
        <!--表中普通字段封装; property:实体类的属性,column:数据库表中的字段名-->
        <result property="usernameabc" column="username"></result>
        <result property="birthdayabc" column="birthday"></result>
        <result property="sexabc" column="sex"></result>
        <result property="addressabc" column="address"></result>
        <!--如果有查询结果有 字段与属性是对应的,可以省略手动封装-->
    </resultMap>

    <select id="findById" parameterType="int" resultType="userResultMap">
        select * from user where id = #{id}
    </select>
</mapper>

多条件查询

方式一

  • 使用 #{arg0}~#{argn} 或者 #{param1}-#{paramn} 获取参数
<mapper namespace="com.lagou.mapper.UserMapper"> 
	<select id="findByIdAndUsername" resultType="user"> 
		<!-- select * from user where id = #{arg0} and username = #{arg1} --> 
		select * from user where id = #{param1} and username = #{param2} 
	</select> 
</mapper>

方式二

  • 使用注解,引入 @Param() 注解获取参数
public List<User> findByIdAndUsername(@Param("id") int id,@Param("username") String username);
<mapper namespace="com.lagou.mapper.UserMapper"> 
	<select id="findByIdAndUsername" resultType="user"> 
		select * from user where id = #{id} and username = #{username} 
	</select> 
</mapper>

方式三(推荐)

  • 直接使用封装好的实体类作为参数
public List<User> findByIdAndUsername(User user);
<mapper namespace="com.lagou.mapper.UserMapper"> 
	<select id="findByIdAndUsername3" parameterType="com.lagou.domain.User" resultType="com.lagou.domain.User"> 
		<!--此时占位符中的id和username就对应user实体中的属性名名-->
		select * from user where id = #{id} and username = #{username} 
	</select> 
</mapper>

模糊查询

方式一

  • 使用#{}
public List<User> findByUsername1(String username);
List<User> list = userMapper.findByUsername1("%王%");
<mapper namespace="com.lagou.mapper.UserMapper"> 
	<select id="findByUsername1" parameterType="string" resultType="user"> 
		<!--当只有一个参数时,占位符中的名字是随便写的,占位符会自动帮我们补全''-->
		select * from user where username like #{username} 
	</select> 
</mapper>

方式二

  • 使用${}
public List<User> findByUsername1(String username);
List<User> list = userMapper.findByUsername1("%王%");
<mapper namespace="com.lagou.mapper.UserMapper"> 
	<select id="findByUsername1" parameterType="string" resultType="user"> 
		<!--当只有一个参数时,${}中必须是value,且不会帮我们自动补全'',且还有sql注入问题-->
		select * from user where username like '${value}' 
	</select> 
</mapper>

${} 与 #{} 区别

  1. #{} :表示一个占位符号
  • 通过 #{} 可以实现preparedStatement向占位符中设置值,自动进行Java实体属性类型和数据库表中字段类型转换,#{}可以有效防止sql注入。
  • #{} 可以接收简单类型值或实体属性值。
  • 如果parameterType传输单个简单类型值, #{} 括号中名称随便写。
  1. ${} :表示拼接sql串
  • 通过 ${} 可以将parameterType 传入的内容拼接在sql中且不进行数据库表中字段类型转换,会出现sql注入问题。
  • ${} 可以接收简单类型值或实体属性值。
  • 如果parameterType传输单个简单类型值, ${} 括号中只能是value。

Mybatis映射文件深入

  • 返回主键:向数据库插入一条记录后,希望能立即拿到这条记录在数据库中的主键值。
  • 方式一:useGeneratedKeys
<!-- 
	useGeneratedKeys="true" 声明返回主键 
	keyProperty="id" 把返回主键的值,封装到实体的id属性中 
	注意:只适用于主键自增的数据库,mysql和sqlserver支持,oracle不支持 
-->
<insert id="save" parameterType="user" useGeneratedKeys="true" keyProperty="id"> 
	INSERT INTO `user`(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address}) 
</insert>

注意:只适用于主键自增的数据库,mysql和sqlserver支持,oracle不行。

  • 方式二: selectKey
<!-- 
	selectKey 适用范围广,支持所有类型数据库 
	keyColumn="id" 指定数据库表中主键列名 
	keyProperty="id" 指定主键封装到实体的id属性中 
	resultType="int" 指定主键类型 
	order="AFTER" 设置在sql语句执行前(后),执行此语句 
-->
<insert id="save" parameterType="user"> 
	<selectKey keyColumn="id" keyProperty="id" resultType="int" order="AFTER"> 
		SELECT LAST_INSERT_ID(); 
	</selectKey> 
	INSERT INTO `user`(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address}) 
</insert>

动态SQL

动态 SQL 之<if>

<!-- where标签相当于 where 1=1,但是如果没有条件,就不会拼接where关键字 --> 
<select id="findByIdAndUsernameIf" parameterType="user" resultType="user"> 
	SELECT * FROM `user` 
	<where> 
		<if test="id != null"> 
			AND id = #{id} 
		</if> 
		<if test="username != null"> 
			AND username = #{username} 
		</if> 
	</where> 
</select>

动态 SQL 之<set>

<!-- set标签在更新的时候,自动加上set关键字,然后去掉最后一个条件的逗号 --> 
<update id="updateIf" parameterType="user"> 
	UPDATE `user` 
		<set>
			<if test="username != null"> 
				username = #{username}, 
			</if> 
			<if test="birthday != null"> 
				birthday = #{birthday}, 
			</if> 
			<if test="sex !=null"> 
				sex = #{sex}, 
			</if> 
			<if test="address !=null"> 
				address = #{address}, 
			</if> 
		</set> 
	WHERE id = #{id} 
</update>

动态 SQL 之<foreach>

foreach主要是用来做数据的循环遍历

<!-- 
	如果查询条件为普通类型 List集合,collection属性值为:collection 或者 list 
	如果查询条件为普通类型 数组,collection属性值为:array
--> 
<select id="findByList" parameterType="list" resultType="user" > 
	SELECT * FROM `user` 
	<where> 
		<foreach collection="collection" open="id in(" close=")" item="id" separator=",">
			#{id} <!--相当于in()这个括号中的内容,id就是item中的id-->
		</foreach> 
	</where> 
</select>

<foreach>标签用于遍历集合,它的属性:
• collection:代表要遍历的集合元素
• open:代表语句的开始部分
• close:代表结束部分
• item:代表遍历集合的每个元素,生成的变量名
• sperator:代表分隔符

Mybatis核心配置文件深入

SQL片段

映射文件中可将重复的 sql 提取出来,使用时用 include 引用即可,最终达到 sql 重用的目的

<!--抽取的sql片段--> 
<sql id="selectUser"> 
	SELECT * FROM `user` 
</sql> 
<select id="findByList" parameterType="list" resultType="user" > 
	<!--引入sql片段--> 
	<include refid="selectUser"></include> 
	<where> 
		<foreach collection="collection" open="id in(" close=")" item="id" separator=",">
			#{id} 
		</foreach> 
	</where> 
</select> 
<select id="findByArray" parameterType="integer[]" resultType="user"> 
<!--引入sql片段--> 
<include refid="selectUser"></include> 
	<where> 
		<foreach collection="array" open="id in(" close=")" item="id" separator=",">
			#{id} 
		</foreach> 
	</where> 
</select>

plugins

MyBatis可以使用第三方的插件来对功能进行扩展,分页助手PageHelper是将分页的复杂操作进行封装,使用简单的方式即可获得分页的相关数据
开发步骤:
①导入通用PageHelper的坐标

<dependency> 
	<groupId>com.github.pagehelper</groupId> 
	<artifactId>pagehelper</artifactId> 
	<version>3.7.5</version> 
</dependency> 
<dependency> 
	<groupId>com.github.jsqlparser</groupId> 
	<artifactId>jsqlparser</artifactId> 
	<version>0.9.1</version> 
</dependency>

②在mybatis核心配置文件中配置PageHelper插件

<!-- 分页助手的插件 --> 
<plugin interceptor="com.github.pagehelper.PageHelper"> 
	<!-- 指定方言 --> 
	<property name="dialect" value="mysql"/> 
</plugin>

③测试分页数据获取

@Test public void testPageHelper(){ 
	//设置分页参数 第一个参数:当前页,第二个参数,每页几条数据
	PageHelper.startPage(1,2); 
	List<User> select = userMapper2.select(); 
	for(User user : select){ 
		System.out.println(user); 
	} 
	//其他分页的数据 
	PageInfo<User> pageInfo = new PageInfo<User>(select); 
	System.out.println("总条数:"+pageInfo.getTotal()); 
	System.out.println("总页数:"+pageInfo.getPages()); 
	System.out.println("当前页:"+pageInfo.getPageNum()); 
	System.out.println("每页显示长度:"+pageInfo.getPageSize()); 
	System.out.println("是否第一页:"+pageInfo.isIsFirstPage()); 
	System.out.println("是否最后一页:"+pageInfo.isIsLastPage());
}

Mybatis多表联合查询

一对一查询

订单表和用户表:一个订单表对应一个用户
1 )Orders实体

@Data
public class Orders {
    private int id;
    private Date ordertime;
    private double total;
    private int uid;
    private User user;
}

2 )OrdersMapper接口

public interface OrdersMapper {
    List<Orders> findOrderWithUser();
}

3 )OrdersMapper.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.lagou.mapper.OrdersMapper">
    <resultMap id="ordersMap" type="orders">
        <id property="id" column="id"></id>
        <result property="ordertime" column="ordertime"></result>
        <result property="total" column="total"></result>
        <result property="uid" column="uid"></result>
        <!--
        	一对一(多对一)使用association标签关联 
        	property="user" 封装实体的属性名 
        	javaType="user" 封装实体的属性类型 
        -->
        <association property="user" javaType="user">
            <id property="id" column="uid"></id>
            <result property="username" column="username"></result>
            <result property="birthday" column="birthday"></result>
            <result property="sex" column="sex"></result>
            <result property="address" column="address"></result>
        </association>
    </resultMap>
    <select id="findOrderWithUser" resultMap="ordersMap">
        SELECT * FROM orders o LEFT JOIN USER u ON u.id = o.uid;
    </select>
</mapper>

4 )查询的结果
在这里插入图片描述

一对多查询

用户表和订单表:一个用户有多个订单
1 )User实体

@Data
public class User {
    private int id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    private List<Orders> ordersList;
}

2 )UserMapper接口

public interface UserMapper {
    List<User> findUserWithOrders();
}

3 )UserMapper.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.lagou.mapper.UserMapper">
    <resultMap id="userMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="birthday" column="birthday"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
        <!--
        	一对多使用collection标签关联 
        	property="orderList" 封装到集合的属性名 
        	ofType="order" 封装集合的泛型类型 
        -->
        <collection property="ordersList" ofType="orders">
            <id property="id" column="oid"></id>
            <result property="ordertime" column="ordertime"></result>
            <result property="total" column="total"></result>
            <result property="uid" column="uid"></result>
        </collection>
    </resultMap>
    <select id="findUserWithOrders" resultMap="userMap">
        SELECT *, o.id oid FROM USER u LEFT JOIN orders o ON u.id = o.uid;
    </select>
</mapper>

4 )查询的结果
在这里插入图片描述

多对多查询

用户表和角色表

1 )User实体

@Data
public class User {
    private int id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    private List<Orders> ordersList;
    private List<Role> roleList;
}

2 )UserMapper接口

public interface UserMapper {
    List<User> findUserWithOrders();

    List<User> findUserWithRole();
}

3 )UserMapper.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.lagou.mapper.UserMapper">
    <resultMap id="userMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="birthday" column="birthday"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
        <collection property="ordersList" ofType="orders">
            <id property="id" column="oid"></id>
            <result property="ordertime" column="ordertime"></result>
            <result property="total" column="total"></result>
            <result property="uid" column="uid"></result>
        </collection>
    </resultMap>
    <select id="findUserWithOrders" resultMap="userMap">
        SELECT *, o.id oid FROM USER u LEFT JOIN orders o ON u.id = o.uid;
    </select>

    <resultMap id="userRoleMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="birthday" column="birthday"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
        <collection property="roleList" ofType="role">
            <id property="id" column="roleid"></id>
            <result property="rolename" column="rolename"></result>
            <result property="roleDesc" column="roleDesc"></result>
        </collection>
    </resultMap>
    <select id="findUserWithRole" resultMap="userRoleMap">
        SELECT * FROM USER u LEFT JOIN sys_user_role sur ON u.id = sur.userid
		                    LEFT JOIN sys_role sr ON sr.id = sur.roleid
    </select>
</mapper>

4 )查询的结果
在这里插入图片描述

MyBatis多表嵌套查询

嵌套查询就是将原来多表查询中的联合查询语句拆成单个表的查询,再使用mybatis的语法嵌套在一起。

一对一嵌套查询

1)OrderMapper接口

public interface OrderMapper { 
	public List<Order> findAllWithUser(); 
}

2)OrderMapper.xml映射

<!--一对一嵌套查询--> 
<resultMap id="orderMap" type="order"> 
	<id column="id" property="id"></id> 
	<result column="ordertime" property="ordertime"></result> 
	<result column="money" property="money"></result> 
	<!--根据订单中uid外键,查询用户表 column就是将findAllWithUser查询出来的表中的字段uid作为参数传递给com.lagou.mapper.UserMapper.findById--> 
	<association property="user" javaType="user" column="uid" select="com.lagou.mapper.UserMapper.findById"></association> 
</resultMap> 
<select id="findAllWithUser" resultMap="orderMap" > SELECT * FROM orders </select>

3)UserMapper接口

public interface UserMapper { 
	public User findById(Integer id); 
}

4)UserMapper.xml映射

<select id="findById" parameterType="int" resultType="user"> 
	SELECT * FROM `user` where id = #{uid} 
</select>

一对多嵌套查询

1)UserMapper接口

public interface UserMapper { 
	public List<User> findAllWithOrder(); 
}

2)UserMapper.xml映射

<!--一对多嵌套查询--> 
<resultMap id="userMap" type="user"> 
	<id column="id" property="id"></id> 
	<result column="username" property="username"></result> 
	<result column="birthday" property="birthday"></result> 
	<result column="sex" property="sex"></result> 
	<result column="address" property="address"></result> 
	<!--根据用户id,查询订单表--> 
	<collection property="orderList" column="id" ofType="order" select="com.lagou.mapper.OrderMapper.findByUid"></collection> 
</resultMap> 
<select id="findAllWithOrder" resultMap="userMap"> SELECT * FROM `user` </select>

3)OrderMapper接口

public interface OrderMapper { 
	public List<Order> findByUid(Integer uid); 
}

4)OrderMapper.xml映射

<select id="findByUid" parameterType="int" resultType="order"> 
	SELECT * FROM orders where uid = #{uid} 
</select>

多对多嵌套查询

1)UserMapper接口

public interface UserMapper { 
	public List<User> findAllWithRole(); 
}

2)UserMapper.xml映射

<!--多对多嵌套查询--> 
<resultMap id="userAndRoleMap" type="user"> 
	<id column="id" property="id"></id> 
	<result column="username" property="username"></result> 
	<result column="birthday" property="birthday"></result> 
	<result column="sex" property="sex"></result> 
	<result column="adress" property="address"></result> 
	<!--根据用户id,查询角色列表--> 
	<collection property="roleList" column="id" ofType="role" select="com.lagou.mapper.RoleMapper.findByUid"></collection> 
</resultMap> 
<select id="findAllWithRole" resultMap="userAndRoleMap">
	SELECT * FROM `user` 
</select>

3)RoleMapper接口

public interface RoleMapper { 
	public List<Role> findByUid(Integer uid); 
}

4)RoleMapper.xml映射

<select id="findByUid" parameterType="int" resultType="role"> 
	SELECT r.id,r.`role_name` roleName,r.`role_desc` roleDesc FROM role r INNER JOIN user_role ur ON r.`id` = ur.`rid` WHERE ur.`uid` = #{uid} 
</select>

优点:简化多表查询操作
缺点:执行多次sql语句,浪费数据库性能

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值