1. MyBatis关联查询简介

  MyBatis中级联分为3中:association、collection及discriminator。

  ◊ association:一对一关联

  ◊ collection:一对多关联

  ◊ discriminator:鉴别器,可以根据实际选择采用哪个类作为实例,允许根据特定的条件去关联不同的结果集。

2. 一对一关联查询

  表结构设计:user、user_profile

2.1 方式一

<?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.libing.helloworld.dao.IUserProfileDao"><resultMap id="baseResultMap" type="com.libing.helloworld.model.UserProfile"><id property="id" column="profile_id" /><result property="userId" column="user_id" /><result property="name" column="name" /><result property="phone" column="phone" /><result property="email" column="email" /><result property="address" column="address" /><association property="user" javaType="com.libing.helloworld.model.User"><id property="id" column="id"/><result property="userName" column="user_name" /><result property="password" column="password" /></association></resultMap><select id="findById" resultMap="baseResultMap">SELECTu.id,u.user_name,u.`password`,user_profile.id profile_id,user_profile.user_id,user_profile.`name`,user_profile.phone,user_profile.email,user_profile.addressFROMuser_profile,`user` uWHEREuser_profile.user_id = u.idAND user_profile.id = #{id}</select>
</mapper>

DEBUG [main] - ==>  Preparing: SELECT u.id, u.user_name, u.`password`, user_profile.id profile_id, user_profile.user_id, user_profile.`name`, user_profile.phone, user_profile.email, user_profile.address FROM user_profile, `user` u WHERE user_profile.user_id = u.id AND user_profile.id = ?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1

2.2 方式二

  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.libing.helloworld.dao.IUserDao"><resultMap id="baseResultMap" type="com.libing.helloworld.model.User"><id property="id" column="id" /><result property="userName" column="user_name" /><result property="password" column="password" /></resultMap><select id="findById" resultMap="baseResultMap">SELECTid,user_name,passwordFROMuserWHERE id = #{id}</select>
</mapper>

  UserProfileMapper.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.libing.helloworld.dao.IUserProfileDao"><resultMap id="baseResultMap" type="com.libing.helloworld.model.UserProfile"><id property="id" column="id" /><result property="userId" column="user_id" /><result property="name" column="name" /><result property="phone" column="phone" /><result property="email" column="email" /><result property="address" column="address" /><association property="user" column="user_id" select="com.libing.helloworld.dao.IUserDao.findById" /></resultMap><select id="findById" resultMap="baseResultMap">SELECTid,user_id,name,phone,email,addressFROMuser_profileWHERE id = #{id}</select>
</mapper>

  UserProfileTest.java:

package com.libing.helloworld.test;import java.io.InputStream;import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.PropertyConfigurator;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;import com.libing.helloworld.dao.IUserProfileDao;
import com.libing.helloworld.model.UserProfile;public class UserProfileTest {SqlSession sqlSession = null;@Beforepublic void init() {PropertyConfigurator.configure(UserProfileTest.class.getClassLoader().getResourceAsStream("log4j.properties"));String resource = "mybatis-config.xml";InputStream inputStream = UserProfileTest.class.getClassLoader().getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);sqlSession = sqlSessionFactory.openSession();}@Testpublic void findById() {try {IUserProfileDao userProfileDao = sqlSession.getMapper(IUserProfileDao.class);UserProfile userProfile = userProfileDao.findById(1);Assert.assertNotNull(userProfile);} catch (Exception e) {e.printStackTrace();} finally {sqlSession.close();}}}

  运行执行的SQL语句:

DEBUG [main] - ==>  Preparing: SELECT id, user_id, name, phone, email, address FROM user_profile WHERE id = ?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - ====>  Preparing: SELECT id, user_name, password FROM user WHERE id = ?
DEBUG [main] - ====> Parameters: 1(Integer)
DEBUG [main] - <====      Total: 1
DEBUG [main] - <==      Total: 1

3. 一对多关联查询

  表结构设计:user、task

3.1 方式一

3.2 方式二

package com.libing.helloworld.model;import java.util.List;public class User {private int id;private String userName;private String password;private List<Task> tasks;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public List<Task> getTasks() {return tasks;}public void setTasks(List<Task> tasks) {this.tasks = tasks;}}

User.java

package com.libing.helloworld.model;public class Task {private int id;private int userId;private String taskName;private String content;public int getId() {return id;}public void setId(int id) {this.id = id;}public int getUserId() {return userId;}public void setUserId(int userId) {this.userId = userId;}public String getTaskName() {return taskName;}public void setTaskName(String taskName) {this.taskName = taskName;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}}

Task.java

<?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.libing.helloworld.dao.ITaskDao"><resultMap id="baseResultMap" type="com.libing.helloworld.model.Task"><id property="id" column="id" /><result property="userId" column="user_id" /><result property="taskName" column="task_name" /><result property="content" column="content" /></resultMap><select id="findTasksByUserId" resultMap="baseResultMap">SELECTid,user_id,task_name,contentFROMtaskWHERE user_id = #{userId}</select>
</mapper>

TaskMapper.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.libing.helloworld.dao.IUserDao"><resultMap id="baseResultMap" type="com.libing.helloworld.model.User"><id property="id" column="id" /><result property="userName" column="user_name" /><result property="password" column="password" /><collection property="tasks" column="id" select="com.libing.helloworld.dao.ITaskDao.findTasksByUserId"></collection></resultMap><select id="findById" resultMap="baseResultMap">SELECTid,user_name,passwordFROMuserWHERE id = #{id}</select>
</mapper>

@Test
public void findAll() {try {IUserDao userDao = sqlSession.getMapper(IUserDao.class);User user = userDao.findById(1);Assert.assertNotNull(user);} catch (Exception e) {e.printStackTrace();} finally {sqlSession.close();}
}

  执行的SQL语句:

DEBUG [main] - ==>  Preparing: SELECT id, user_name, password FROM user WHERE id = ?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - ====>  Preparing: SELECT id, user_id, task_name, content FROM task WHERE user_id = ?
DEBUG [main] - ====> Parameters: 1(Integer)
DEBUG [main] - <====      Total: 0
DEBUG [main] - <==      Total: 1

4. N + 1问题

5. 延迟加载

转载于:https://www.cnblogs.com/libingql/p/7517310.html

MyBatis基础:MyBatis关联查询(4)相关推荐

  1. mybatis中的关联查询

    mybatis中的关联查询 (尊重劳动成果,转载请注明出处:https://blog.csdn.net/qq_39778516/article/details/84191429 consistence ...

  2. mybatis一对多关联查询两种方式

    mybatis一对多关联查询两种方式 前提: 方式一: 方式二: 前提: 现在有两张表,学生表跟教师表,一个教师对应多个学生 教师表: CREATE TABLE `teacher` (`id` int ...

  3. 14、mybatis多表关联查询 association定义关联对象封装规则及懒加载

    文章目录 1.使用association单步查询 1).EmployeeMapper 2).EmployeeMapper.xml 3).Test 2.使用association进行分步查询 4).De ...

  4. 13、mybatis多表关联查询级联属性

    文章目录 1.创建表结构 2.EmployeeMapper接口 3.EmployeeMapper.xml 4.Test 1.创建表结构 CREATE TABLE `mybatis`.`dept` (` ...

  5. mybatis collection_MyBatis之关联查询

    前言 我们进行数据库查询时往往需要的不止一张表的数据,需要将多张表的数据一起查询出来,大家学习过数据库的连接查询,那么在MyBatis中如何将有关系的多张表数据进行关联查询呢. 表的结构 商品和订单是 ...

  6. mybatis 多表关联查询_Java修行第041天--MyBatis框架(下)--多表查询

    1 解决列名和属性名不一致问题 如果查询时使用 resultType 属性, 表示采用 MyBatis 的Auto-Mapping(自动映射)机制, 即相同的列名和属性名会自动匹配. 因此, 当数据库 ...

  7. 【mybatis】一对一关联查询

    mybatis: 一对一关联查询 注意 代码部分 实体类(extity) mybatis mapper service controller 注意 在.xml文件编写中有报错,The content ...

  8. Mybatis多表关联查询(一对多关联查询)

    1.Mybatis一级缓存与二级缓存 目的:提高查询效率,降低数据库查询压力,提升系统整体性能. 一级缓存:默认开启,Session级别,同一个会话内生效. 命中缓存的情况:statementid.S ...

  9. Mybatis一对多关联查询,返回值Map,字段自动映射

    功能描述 由于查询字段和表名都要支持动态配置,故查询返回值需要为List<Map<String,Object>>,不定义值对象. 查询结果列需要支持自动映射,不配置类属性和数据 ...

  10. mybatis一对多关联查询将结果封装到嵌套list

    DishDto中有个List集合保存DishFlavor对象,DishFlavor根据关联查询获得,一个dish对应多个dishflavor.想要联合查询自动将DishFlavor封装成集合需要用co ...

最新文章

  1. 定义查询构建器IFeatureLayerDefinition
  2. Oracle中快速查找锁与锁等待
  3. VMware Workstation Pro 无法在Windows上运行的解决方案
  4. UI组件之AdapterView及其子类(四)Gallery画廊控件使用
  5. 分数的计算机应用教案,计算机应用实训实验
  6. python数据分析之matplotlib绘图
  7. 【转】如何把Matlab中的m文件转化成C语言代码
  8. 同步 IO 和异步 IO
  9. oracle数据库中文乱码解决办法
  10. UA MATH563 概率论的数学基础 中心极限定理1 随机变量序列的收敛
  11. 服务器的mib文件,snmp 服务器增加 mib
  12. linux写含输入输出的代码,linux系统管理-输入输出
  13. PythonSPSS完成空气质量状况的指数(AQI)分析
  14. 关于概率论和模糊数学的区别
  15. EXSI 中新建虚拟机
  16. utf8和utf8mb4的区分
  17. ARFoundation之路-环境配置(iOS)之二
  18. iOS小技巧11-Xcode中相对路径和绝对路径的使用
  19. vostro3070装win7_戴尔Vostro 成就 3070台式机装win7系统及bios设置
  20. (转)iOS Wow体验 - 第四章 - 为应用的上下文环境而设计

热门文章

  1. python装饰器副作用_对Python 装饰器的理解心得
  2. SQL数据库权限授予grant
  3. 15.7 擦除的神秘之处
  4. Android.mk文件的解析
  5. struts2 去掉或修改后缀名
  6. 深入探讨 java.lang.ref 包
  7. Ocelot简易教程(七)之配置文件数据库存储插件源码解析
  8. Matlab变量、分支语句和循环语句
  9. iOS开发学习之MapKit - 获得在MapView(地图)中显示多个标记的区域(MKCoordinateRegion)...
  10. OpenCV条码(6)简单实现