本文将介绍怎样利用 <select> 标签的 resultMap 属性引用 <resultMap> 标签,实现 MyBatis 的结果映射。
结果映射是 MyBatis 最强大的特性,如果你对其理解透彻,许多复杂的映射问题都能迎刃而解。
注意:<select> 标签的 resultType 和 resultMap 属性只能同时使用一个。而且,本章节不介绍 <resultMap> 标签的具体用法,你只需了知道 <resultMap> 标签用于结果集映射即可,后续章节将详细介绍 <resultMap> 标签的用法。
本实例将分别介绍单张表数据查询结果映射,和一个复杂的SQL查询结果映射(即多张表进行JOIN查询结果)。
(1)首先配置MyBatis,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/select/demo2/UserMapper.xml" /> </mappers> </configuration>
上面配置只是简单的配置了数据源和Mapper文件资源。
(2)定义 Mapper 接口,下面将定义两个接口,第一个根据用户ID查询用户信息(单表查询),第二个根据用ID查询用户拥有的书籍(多表查询)。UserMapper.java 文件内容如下:
package com.hxstrive.mybatis.select.demo2; import org.apache.ibatis.annotations.Param; import java.util.List; public interface UserMapper { /** 根据ID查询用户信息 */ UserBean getUserById(@Param("userId") int userId); /** 根据用户ID查询用户拥有的书籍信息 */ List<UserBookBean> getUserBook(@Param("userId") int userId); }
(3)根据 Mapper 接口编写 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.select.demo2.UserMapper"> <!-- 映射结果 --> <resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.select.demo2.UserBean"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="sex" jdbcType="VARCHAR" property="sex" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <!-- 根据ID查询用户信息 --> <select id="getUserById" parameterType="int" resultMap="RESULT_MAP"> select `user_id`, `name`, `sex`, `age` from `user` where `user_id`=#{userId,jdbcType=INTEGER} </select> <!-- 结果映射 --> <resultMap id="RESULT_MAP2" type="com.hxstrive.mybatis.select.demo2.UserBookBean"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <result column="username" jdbcType="VARCHAR" property="username" /> <result column="age" jdbcType="INTEGER" property="age" /> <result column="book_name" jdbcType="VARCHAR" property="bookName" /> <result column="price" jdbcType="DOUBLE" property="price" /> </resultMap> <!-- 根据用户ID查询用户拥有的书籍信息 --> <select id="getUserBook" parameterType="int" resultMap="RESULT_MAP2"> SELECT u.user_id, u.`name` as username, u.age, b.book_name, b.price FROM `user` u join `user_book` ub on u.user_id=ub.user_id join `book` b on b.book_id=ub.book_id where u.user_id=#{userId,jdbcType=INTEGER} </select> </mapper>
(4)分别定义单表和多表查询结果JavaBean。如下:
a、UserBean.java
package com.hxstrive.mybatis.select.demo2; public class UserBean { private Integer userId; private String name; private String sex; private Integer age; // 忽略 setter 和 getter @Override public String toString() { return "UserBean{" + "userId=" + userId + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + '}'; } }
b、UserBookBean.java
package com.hxstrive.mybatis.select.demo2; public class UserBookBean { private int userId; private String username; private int age; private String bookName; private float price; // 忽略 setter 和 getter @Override public String toString() { return "UserBookBean{" + "userId=" + userId + ", username='" + username + '\'' + ", age=" + age + ", bookName='" + bookName + '\'' + ", price=" + price + '}'; } }
(5)客户端,调用定义的接口。如下:
package com.hxstrive.mybatis.select.demo2; 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 SelectDemo2 { public static void main(String[] args) throws Exception { String cfgName = "com/hxstrive/mybatis/select/demo2/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); // 单表查询 UserBean userBean = userMapper.getUserById(1); System.out.println(userBean); // 多表查询 List<UserBookBean> userBookBeanList = userMapper.getUserBook(1); for(UserBookBean userBookBean : userBookBeanList) { System.out.println(userBookBean); } } }
运行结果如下:
UserBean{userId=1, name='张三', sex='男', age=28} UserBookBean{userId=1, username='张三', age=28, bookName='《Java编程思想》', price=85.5} UserBookBean{userId=1, username='张三', age=28, bookName='《编码》', price=42.48}
更多关于结果映射请阅读“什么是结果映射?”章节。