mybatis都会用,但要优雅的用就不是那么容易了

今天就简单举例,抛砖引玉,供大家探讨

1.主表

CREATE TABLE `test_one` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nickname` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

对应的java实体类如下(自动生成的代码,省略get set)

@JsonIgnoreProperties(ignoreUnknown = true, value = {"handler"})
public class TestOne implements Serializable {
private static final long serialVersionUID = 1L; private Integer id; private String nickname; @JsonIgnoreProperties(ignoreUnknown = true, value = {"testOne"})
private List<TestTwo> testTwos = new LinkedList<>();

注意:JsonIgnoreProperties请忽略,这是解决对象间循环依赖在json序列化时出错的,不在本次内容中

2.从表

CREATE TABLE `test_two` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nickname` varchar(255) NOT NULL,
`one_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `test_two_ibfk_1` (`one_id`),
CONSTRAINT `test_two_ibfk_1` FOREIGN KEY (`one_id`) REFERENCES `test_one` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

对应的java实体类如下(自动生成的代码,省略get set)

@JsonIgnoreProperties(ignoreUnknown = true, value = {"handler"})
public class TestTwo implements Serializable {
private Integer id; private String nickname; private Integer oneId; @JsonIgnoreProperties(ignoreUnknown = true, value = {"testTwos"})
private TestOne testOne;

注意:JsonIgnoreProperties请忽略,这是解决对象间循环依赖在json序列化时出错的,不在本次内容中

细心的同学发现,两个表用同名字段,后续会告诉为什么这么举例,而且这种情况项目中是非常常见的

3.TestOneMapper.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="info.zycloud.xcx.merchant.dao.TestOneMapper">
<resultMap id="BaseResultMap" type="info.zycloud.xcx.merchant.model.TestOne">
<constructor>
<idArg column="id" javaType="java.lang.Integer" jdbcType="INTEGER"/>
<arg column="nickname" javaType="java.lang.String" jdbcType="VARCHAR"/>
</constructor>
</resultMap> <!--一次查询查出collection-->
    这里会一次查询就查询出主对象和关联的list对象, 查询语句是一个join语句
<resultMap id="OnceQueryBaseResultMap" type="info.zycloud.xcx.merchant.model.TestOne" extends="BaseResultMap">
<collection property="testTwos" resultMap="info.zycloud.xcx.merchant.dao.TestTwoMapper.BaseResultMap"
columnPrefix="two_"/> 由于两个表有同名字段,所以需要做区分,这里可以采用前缀,就可以共用之前的ResultMap了
</resultMap>

<select id="onceQuery4Collection" resultMap="OnceQueryBaseResultMap">
SELECT
one.*,  为什么要用*,是为了防止主表字段变了,因为这里是引用的生成的baseresultMap
two.id AS two_id,
two.nickname AS two_nickname,
two.one_id AS two_one_id
FROM
`test_one` one
LEFT JOIN test_two two ON one.id = two.one_id
</select> <!-- 多次查询查出collection-->
<resultMap id="MultipleQueryBaseResultMap" type="info.zycloud.xcx.merchant.model.TestOne" extends="BaseResultMap">
<collection property="testTwos" column="{oneId=id,nickname=nickname}" 多参数时在column中用"{}"将参数包起来, =左侧的为mapper中定义的param, =右侧为主查询的数据库字段名  
select="info.zycloud.xcx.merchant.dao.TestTwoMapper.selectByOneId"/>
</resultMap> <select id="multipleQuery4Collection" parameterType="java.lang.Integer" resultMap="MultipleQueryBaseResultMap">
select
<include refid="Base_Column_List"/>
from test_one
where id = #{id,jdbcType=INTEGER}
</select> </mapper>

对应的接口定义

 public interface TestOneMapper {

     List<TestOne> onceQuery4Collection();

     TestOne multipleQuery4Collection(Integer id);
}

3.TestTwoMapper.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="info.zycloud.xcx.merchant.dao.TestTwoMapper">
<resultMap id="BaseResultMap" type="info.zycloud.xcx.merchant.model.TestTwo">
<constructor>
<idArg column="id" javaType="java.lang.Integer" jdbcType="INTEGER"/>
<arg column="nickname" javaType="java.lang.String" jdbcType="VARCHAR"/>
<arg column="one_id" javaType="java.lang.Integer" jdbcType="INTEGER"/>
</constructor>
</resultMap> <select id="selectByOneId" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from test_two
where one_id=#{oneId} and nickname =#{nickname}
</select>
</mapper>
 public interface TestTwoMapper {
List<TestTwo> selectByOneId(@Param("oneId") Integer oneId, @Param("nickname") String nickname);
}

解释了然后我们执行看下效果:

onceQuery4Collection:

multipleQuery4Collection:

mybatis中collection association优化使用及多参数传递的更多相关文章

  1. Mybatis中使用association进行关联的几种方式

    这里以一对一单向关联为例.对使用或不使用association的配置进行举例.  实体类: @Data @ToString @NoArgsConstructor public class IdCard ...

  2. mybatis中collection和association的作用以及用法

    deptDaoMapper.xml 部门对应员工(1对多的关系) <resultMap type="com.hw.entity.Dept" id="deptinfo ...

  3. Mybatis中collection和association的使用区别

    1. 关联-association2. 集合-collection 比如同时有User.java和Card.java两个类 User.java如下: public class User{ privat ...

  4. Mybatis中使用association及collection进行自关联示例(含XML版与注解版)

    XML版本: 实体类: @Data @ToString @NoArgsConstructor public class Dept { private Integer id; private Strin ...

  5. Mybatis中使用association及collection进行一对多双向关联示例(含XML版与注解版)

    XML版本: 实体类: package com.sunwii.mybatis.bean; import java.util.ArrayList; import java.util.List; impo ...

  6. Mybatis中 collection 和 association 的区别

    public class A{ private B b1; private List<B> b2;} 在映射b1属性时用association标签,(一对一的关系) 映射b2时用colle ...

  7. Mybatis中 collection 和 association 的区别?

    public class A{ private B b1; private List<B> b2;} 在映射b1属性时用association标签,(一对一的关系) 映射b2时用colle ...

  8. Mybatis中collection与association的区别

    association是多对一的关系 collection是一个一对多的关系

  9. myBatis中 collection 或 association 联合查询 中column 传入多个参数值

    下面是一个树形结构表自连接 联合查询 Demo <resultMap id="BaseResultMap"  type="com.maidan.daas.entit ...

随机推荐

  1. HOWTO: Avizo/Amira/Pergeos中如何利用Volume Edit

    操作非常简单,就是利用Volume Edit取圆柱的同时可以取一个Mask(或称之为ROI,感兴趣区域,蒙板等) 如上图,利用Volume Edit取一个圆柱,然后点击Create Mask创建一个M ...

  2. Unity进阶:用AssetBundle和Json做了一个玩家登陆界面

    版权申明: 本文原创首发于以下网站: 博客园『优梦创客』的空间:https://www.cnblogs.com/raymondking123 优梦创客的官方博客:https://91make.top ...

  3. JavaScript Array 数组方法汇总

    JavaScript Array 数组方法汇总 1. arr.push() 从后面添加元素,返回值为添加完后的数组的长度 var arr = [1,2,3,4,5] console.log(arr.p ...

  4. Oracle批量更改所有表的字段取值_类型_原字段名

    CREATE PROCEDURE 存储过程名称 is cursor c_tab is select * from user_tab_columns t r_tab user_tab_columns%r ...

  5. POJ-3660 Cow Contest( 最短路 )

    题目链接:http://poj.org/problem?id=3660 Description N (1 ≤ N ≤ 100) cows, conveniently numbered 1..N, ar ...

  6. CodeForces 1083 E The Fair Nut and Rectangles 斜率优化DP

    The Fair Nut and Rectangles 题意:有n个矩形,然后你可以选择k个矩形,选择一个矩形需要支付代价 ai, 问 总面积- 总支付代价 最大能是多少, 保证没有矩形套矩形. 题解 ...

  7. codeforces E. Okabe and El Psy Kongroo(dp+矩阵快速幂)

    题目链接:http://codeforces.com/contest/821/problem/E 题意:我们现在位于(0,0)处,目标是走到(K,0)处.每一次我们都可以从(x,y)走到(x+1,y- ...

  8. CF1005E1 Median on Segments (Permutations Edition) 思维

    Median on Segments (Permutations Edition) time limit per test 3 seconds memory limit per test 256 me ...

  9. Linux开机启动过程(个人理解)

    简述Linux启动过程 1)BIOS开机自检 2)MBR引导 3)启动引导程序菜单(GRUB) 4)加载内核 5)加载虚拟文件系统加载函数模块 6)启动系统进程 /sbin/init --->/ ...

  10. nvm 管理多个活动的node.js版本

    前序:最近在使用taro框架开发小程序,因为安装taro时遇到一些问题,后来重新安装了node版本——v10.16.3,却影响了我本地开发的项目,故此使用nvm来管理node的版本,更加灵活的切换以支 ...