本章节将介绍 <discriminator> 标签的用法,<discriminator> 标签使用比其他标签稍微复杂一些。该标签用来根据列的值,选择不同的结果映射。例如:
<discriminator column="type" javaType="INTEGER"> <case value="1" resultMap="BOOK_RESULT_MAP" /> <case value="2" resultMap="CONTACT_RESULT_MAP" /> </discriminator>
上面映射中,将根据 type 数据类的值,动态决定使用 BOOK_RESULT_MAP 或 CONTACT_RESULT_MAP 结果集映射。其中:
column:指定一个数据列名,该列名将用来实现动态选择结果集映射,如:type
javaType:指定 column 指定的数据列在 Java 中的数据类型,如:INTEGER
<case> 标签用来映射一个条件分支,上面就使用两个 <case> 标签映射两个映射分支。其中:
value:用来指定匹配当前条件分支的数据列值,如:type 列等于 1
resultMap:用来指定一个结果集映射的ID,如:BOOK_RESULT_MAP
其实,<discriminator> 标签就是一个标签样式的 switch 语句。如上示例,当 type 等于 1,则选择 BOOK_RESULT_MAP 结果集映射;当 type 等于 2,则选择 CONTACT_RESULT_MAP 结果集映射。转成 switch 语句如下:
String resultMap = ""; switch(type) { case 1: resultMap = "BOOK_RESULT_MAP"; break; case 2: resultMap = "CONTACT_RESULT_MAP"; break; }
(1)MyBatis 配置文件 mybatis-cfg.xml 内容如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="database.properties"/> <environments default="MySqlDatabase" > <environment id="MySqlDatabase" > <transactionManager type="JDBC" /> <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="com\hxstrive\mybatis\resultmap\demo8\UserMapper.xml" /> </mappers> </configuration>
(2)UserBean、SubBean、BookBean 和 ContactBean 代码如下:
a、UserBean.java
public class UserBean { private Integer userId; private String name; private String sex; private Integer age; private List<SubBean> subList; public UserBean(Integer userId, String name) { this.userId = userId; this.name = name; } // 忽略 getter 和 setter @Override public String toString() { StringBuilder subStrs = new StringBuilder(); for(SubBean sub : subList) { subStrs.append("\n\t").append(sub.toString()); } return "UserBean{" + "userId=" + userId + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + "} " + subStrs; } }
b、SubBean.java
package com.hxstrive.mybatis.resultmap.demo8; public class SubBean { private Integer subId; }
c、BookBean.java
package com.hxstrive.mybatis.resultmap.demo8; public class BookBean extends SubBean { private String bookName; private Float price; private String content; // 忽略 getter 和 setter @Override public String toString() { return "BookBean{" + "bookId=" + getSubId() + ", bookName='" + bookName + '\'' + ", price=" + price + ", content='" + content + '\'' + '}'; } }
d、ContactBean.java
package com.hxstrive.mybatis.resultmap.demo8; public class ContactBean extends SubBean { private String usage; private String number; // 忽略 getter 和 setter @Override public String toString() { return "ContactBean{" + "id=" + getSubId() + ", usage='" + usage + '\'' + ", number='" + number + '\'' + '}'; } }
(3)Mapper 接口文件 UserMapper.java 代码如下:
package com.hxstrive.mybatis.resultmap.demo8; import java.util.List; public interface UserMapper { /** 查询所有用户信息 */ List<UserBean> findAll(); }
(4)Mapper XML 文件 UserMapper.xml 代码如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hxstrive.mybatis.resultmap.demo8.UserMapper"> <!-- 定义 book 表的映射 --> <resultMap id="BOOK_RESULT_MAP" type="com.hxstrive.mybatis.resultmap.demo8.BookBean"> <result column="book_name" jdbcType="VARCHAR" property="bookName" /> <result column="price" jdbcType="FLOAT" property="price" /> <result column="content" jdbcType="VARCHAR" property="content" /> </resultMap> <!-- 定义 contact 表的映射 --> <resultMap id="CONTACT_RESULT_MAP" type="com.hxstrive.mybatis.resultmap.demo8.ContactBean"> <result column="contact_usage" jdbcType="VARCHAR" property="usage" /> <result column="contact_number" jdbcType="VARCHAR" property="number" /> </resultMap> <!-- 定义SQL语句映射 --> <resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.resultmap.demo8.UserBean"> <constructor> <idArg column="user_id" javaType="int" /> <arg column="name" javaType="String" /> </constructor> <result column="sex" jdbcType="VARCHAR" property="sex" /> <result column="age" jdbcType="INTEGER" property="age" /> <collection property="subList" ofType="com.hxstrive.mybatis.resultmap.demo8.SubBean"> <id column="sub_id" jdbcType="INTEGER" property="subId" /> <!-- 根据 type 列来选择不同的 resultMap --> <discriminator column="type" javaType="INTEGER"> <case value="1" resultMap="BOOK_RESULT_MAP" /> <case value="2" resultMap="CONTACT_RESULT_MAP" /> </discriminator> </collection> </resultMap> <select id="findAll" resultMap="RESULT_MAP"> select u.`user_id`, u.`name`, u.`sex`, u.`age`, ifnull(bk.book_id, ct.id) as sub_id, ifnull(bk.type, ct.type) as type, bk.book_name, bk.price, bk.content, ct.`usage` as contact_usage, ct.number as contact_number from `user` u left join ( select 1 as type, ub.user_id, b.* from `user_book` ub join `book` b on b.book_id=ub.book_id ) bk on bk.user_id=u.user_id left join ( select 2 as type, t.* from `user_contact` t ) ct on ct.user_id=u.user_id </select> </mapper>
(5)客户端代码如下:
package com.hxstrive.mybatis.resultmap.demo8; 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 java.io.InputStream; import java.util.List; public class ResultMapDemo8 { public static void main(String[] args) throws Exception { // 获取 Mapper 对象 String cfgName = "com/hxstrive/mybatis/resultmap/demo8/mybatis-cfg.xml"; InputStream input = Resources.getResourceAsStream(cfgName); SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlFactory = factoryBuilder.build(input); SqlSession sqlSession = sqlFactory.openSession(true); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<UserBean> userBeanList = userMapper.findAll(); for(UserBean userBean : userBeanList) { System.out.println("结果:" + userBean); } } }