使用XML嵌套的方式实现关联查询有两种方式,第一种方式使用嵌套查询的方式,这种方式可能会带来多次查询的问题,效率低下。另一个方式为关联查询,结果嵌套的方式,效率比较理想。
例子为一个省份表,一个城市表,城市有一个字段关联省份,通过ID查询某个城市,关联获取省份的实体
本项目搭建源码:https://github.com/zhuquanwen/mybatis-learn/releases/tag/for-xml-association
搭建过程:
在https://blog.csdn.net/u011943534/article/details/104911104文章基础上搭建,有些过程不详细描述.
一、查询嵌套的方式
1、导入本文测试使用的sql脚本
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50722
Source Host : localhost:3306
Source Database : mybatis_learn
Target Server Type : MYSQL
Target Server Version : 50722
File Encoding : 65001
Date: 2020-09-04 21:22:20
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for province
-- ----------------------------
DROP TABLE IF EXISTS `province`;
CREATE TABLE `province` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of province
-- ----------------------------
INSERT INTO `province` VALUES ('1', '黑龙江');
INSERT INTO `province` VALUES ('2', '湖南');
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50722
Source Host : localhost:3306
Source Database : mybatis_learn
Target Server Type : MYSQL
Target Server Version : 50722
File Encoding : 65001
Date: 2020-09-04 21:23:33
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for city
-- ----------------------------
DROP TABLE IF EXISTS `city`;
CREATE TABLE `city` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`pid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `pid` (`pid`),
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `province` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records of city
-- ----------------------------
INSERT INTO `city` VALUES ('1', '哈尔滨', '1');
INSERT INTO `city` VALUES ('2', '黑河', '1');
INSERT INTO `city` VALUES ('3', '牡丹江', '1');
INSERT INTO `city` VALUES ('4', '齐齐哈尔', '1');
INSERT INTO `city` VALUES ('5', '大庆', '1');
INSERT INTO `city` VALUES ('6', '鸡西', '1');
INSERT INTO `city` VALUES ('7', '长沙', '2');
INSERT INTO `city` VALUES ('8', '衡阳', '2');
INSERT INTO `city` VALUES ('9', '湘潭', '2');
2 配置generator插件,之后运行com.learn.zqw.generator.Generator的主函数将bird表自动生成实体和mapper
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- context指定环境 -->
<context id="MyGererator" targetRuntime="MyBatis3">
<!-- 这个标签可以去掉各类元素生成的注释,默认是全部生成的 -->
<commentGenerator>
<!-- 去掉注释 -->
<property name="suppressAllComments" value="true"/>
<!-- 去掉时间戳 -->
<property name="suppressDate" value="true"/>
</commentGenerator>
<!-- 数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis_learn?useUnicode=true&characterEncoding=utf8"
userId="root"
password="root">
</jdbcConnection>
<!-- JAVA JDBC数据类型转换,可以参照官方文档 -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- javaModelGenerator javaBean配置
targetPackage 输入包名 输出路径
targetProject 输出项目位置 -->
<javaModelGenerator targetPackage="com.learn.zqw.association.domain" targetProject="src/main/java">
<!-- enableSubPackages 是否开启子包名称 是否在包名后边加上scheme名称 -->
<property name="enableSubPackages" value="false" />
<!-- 在Set方法中加入.trim -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 映射文件mapper.xml配置 -->
<sqlMapGenerator targetPackage="com.learn.zqw.association.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 动态代理类接口,和mapper.xml在要同一个路径 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.learn.zqw.association.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 数据表 根据数据库中的表来生成 -->
<!--<table tableName="student"/>-->
<!--<table tableName="bird"/>-->
<table tableName="province"/>
<table tableName="city"/>
<!-- 数据表更详细的属性参见官方文档,也可参照https://www.jianshu.com/p/e09d2370b796,里注释掉-->
<!-- <table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" >
<property name="useActualColumnNames" value="true"/>
<generatedKey column="ID" sqlStatement="DB2" identity="true" />
<columnOverride column="DATE_FIELD" property="startDate" />
<ignoreColumn column="FRED" />
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
</table> -->
</context>
</generatorConfiguration>
3 修改Citpy实体,添加Province
package com.learn.zqw.association.domain;
import lombok.Data;
@Data
public class City {
private Integer id;
private String name;
private Integer pid;
private Province province;
}
4 在自动生成的CityMapper中添加一个关联ResultMap,使用了association 标签,com.learn.zqw.association.mapper.ProvinceMapper.selectByPrimaryKey为ProvinceMapper中的一个函数
<resultMap id="ResultMapWithProvince" type="com.learn.zqw.association.domain.City">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="pid" jdbcType="INTEGER" property="pid" />
<association property="province" column="pid" select="com.learn.zqw.association.mapper.ProvinceMapper.selectByPrimaryKey"/>
</resultMap>
5 在自动生成的CityMapper中添加一个查询select,引用上面定义的ResultMapWithProvince
<select id="selectWithProvinceById" parameterType="java.lang.Integer" resultMap="ResultMapWithProvince">
select id,name,pid from city where id = #{
id, jdbcType=INTEGER}
</select>
6 在generatorConfig.xml中添加两个Mapper
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- context指定环境 -->
<context id="MyGererator" targetRuntime="MyBatis3">
<!-- 这个标签可以去掉各类元素生成的注释,默认是全部生成的 -->
<commentGenerator>
<!-- 去掉注释 -->
<property name="suppressAllComments" value="true"/>
<!-- 去掉时间戳 -->
<property name="suppressDate" value="true"/>
</commentGenerator>
<!-- 数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis_learn?useUnicode=true&characterEncoding=utf8"
userId="root"
password="root">
</jdbcConnection>
<!-- JAVA JDBC数据类型转换,可以参照官方文档 -->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- javaModelGenerator javaBean配置
targetPackage 输入包名 输出路径
targetProject 输出项目位置 -->
<javaModelGenerator targetPackage="com.learn.zqw.association.domain" targetProject="src/main/java">
<!-- enableSubPackages 是否开启子包名称 是否在包名后边加上scheme名称 -->
<property name="enableSubPackages" value="false" />
<!-- 在Set方法中加入.trim -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 映射文件mapper.xml配置 -->
<sqlMapGenerator targetPackage="com.learn.zqw.association.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 动态代理类接口,和mapper.xml在要同一个路径 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.learn.zqw.association.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 数据表 根据数据库中的表来生成 -->
<!--<table tableName="student"/>-->
<!--<table tableName="bird"/>-->
<table tableName="province"/>
<table tableName="city"/>
<!-- 数据表更详细的属性参见官方文档,也可参照https://www.jianshu.com/p/e09d2370b796,里注释掉-->
<!-- <table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" >
<property name="useActualColumnNames" value="true"/>
<generatedKey column="ID" sqlStatement="DB2" identity="true" />
<columnOverride column="DATE_FIELD" property="startDate" />
<ignoreColumn column="FRED" />
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
</table> -->
</context>
</generatorConfiguration>
7 测试
package com.learn.zqw.association;
import com.learn.zqw.association.domain.City;
import com.learn.zqw.association.mapper.CityMapper;
import lombok.Cleanup;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.IOException;
import java.io.InputStream;
/**
* //TODO
*
* @author zhuquanwen
* @vesion 1.0
* @date 2020/9/4 20:58
* @since jdk1.8
*/
@RunWith(JUnit4.class)
public class AssociationTests {
@Test
public void test() throws IOException {
@Cleanup InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession session = sessionFactory.openSession();
CityMapper mapper = session.getMapper(CityMapper.class);
City city = mapper.selectWithProvinceById(1);
System.out.println(city);
}
}
测试结果:
[2020/09/04 21:18:16,697] [DEBUG] [org.apache.ibatis.transaction.jdbc.JdbcTransaction:100] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@475e586c]
[2020/09/04 21:18:16,704] [DEBUG] [com.learn.zqw.association.mapper.CityMapper.selectWithProvinceById:143] - ==> Preparing: select id,name,pid from city where id = ?
[2020/09/04 21:18:16,738] [DEBUG] [com.learn.zqw.association.mapper.CityMapper.selectWithProvinceById:143] - ==> Parameters: 1(Integer)
[2020/09/04 21:18:16,762] [DEBUG] [com.learn.zqw.association.mapper.ProvinceMapper.selectByPrimaryKey:143] - ====> Preparing: select id, name from province where id = ?
[2020/09/04 21:18:16,762] [DEBUG] [com.learn.zqw.association.mapper.ProvinceMapper.selectByPrimaryKey:143] - ====> Parameters: 1(Integer)
[2020/09/04 21:18:16,769] [DEBUG] [com.learn.zqw.association.mapper.ProvinceMapper.selectByPrimaryKey:143] - <==== Total: 1
[2020/09/04 21:18:16,770] [DEBUG] [com.learn.zqw.association.mapper.CityMapper.selectWithProvinceById:143] - <== Total: 1
[2020/09/04 21:18:16,770] [DEBUG] [com.learn.zqw.plugin.TestPlugin:38] - 耗时:413ms
City(id=1, name=哈尔滨, pid=1, province=Province(id=1, name=黑龙江))
Process finished with exit code 0
二、查询结果嵌套的方式
1 在CityMapper.xml种添加ResultSetMap
<resultMap id="ResultMapWithProvince2" type="com.learn.zqw.association.domain.City">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<association property="province" javaType="com.learn.zqw.association.domain.Province">
<id column="id" javaType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name" />
</association>
</resultMap>
2 在CityMapper.xml种添加select
<select id="selectWithProvinceById2" parameterType="java.lang.Integer" resultMap="ResultMapWithProvince2">
select c.id,c.name,c.pid,p.id, p.name from city c, province p where c.pid = p.id and c.id = #{
id, jdbcType=INTEGER}
</select>
3 在CityMapper.xml种添加接口
City selectWithProvinceById2(Integer id);
4 测试
@Test
public void test2() throws IOException {
@Cleanup InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession session = sessionFactory.openSession();
CityMapper mapper = session.getMapper(CityMapper.class);
City city = mapper.selectWithProvinceById2(1);
System.out.println(city);
}
测试结果:
[2020/09/05 21:03:41,388] [DEBUG] [org.apache.ibatis.transaction.jdbc.JdbcTransaction:100] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@475e586c]
[2020/09/05 21:03:41,400] [DEBUG] [com.learn.zqw.association.mapper.CityMapper.selectWithProvinceById2:143] - ==> Preparing: select c.id,c.name,c.pid,p.id, p.name from city c, province p where c.pid = p.id and c.id = ?
[2020/09/05 21:03:41,453] [DEBUG] [com.learn.zqw.association.mapper.CityMapper.selectWithProvinceById2:143] - ==> Parameters: 1(Integer)
[2020/09/05 21:03:41,496] [DEBUG] [com.learn.zqw.association.mapper.CityMapper.selectWithProvinceById2:143] - <== Total: 1
[2020/09/05 21:03:41,497] [DEBUG] [com.learn.zqw.plugin.TestPlugin:38] - 耗时:668ms
City(id=1, name=哈尔滨, pid=null, province=Province(id=1, name=哈尔滨))
Process finished with exit code 0
三、 两种方式对比
对比两种测试结果的输出会发现第一种方式输出了两条SQL,第二种方式只输出一条。