本章节将介绍 <collection> 标签的用法,<collection> 标签用于实现一对多关联关系映射。例如,一个用户拥有多本书。下面将通过一个实例学习 <association> 标签的用法:
(1)假设我们有如下一个稍微复杂的SQL语句,用来查询用户拥有的书籍列表。如下:
select u.`user_id`, u.`name`, u.`sex`, u.`age`, b.book_id, b.book_name, b.price, b.content from `user` u join `user_book` ub on u.user_id=ub.user_id join `book` b on b.book_id=ub.book_id
其中,user_book 表是一张中间表,保存书籍和用户的关系。
(2)我们根据上面 SQL 定义了如下 UserBean 和 BookBean,代码如下:
public class UserBean { private Integer userId; private String name; private String sex; private Integer age; // 用来存放用户关联的多本书籍 private List<BookBean> bookList; public UserBean(Integer userId, String name) { this.userId = userId; this.name = name; } // 忽略 getter 和 setter }
BookBean 代码如下:
public class BookBean { private Integer bookId; private String bookName; private Float price; private String content; // 忽略了 getter 和 setter 方法 }
(3)接下来我们就需要使用 XML Mapper 文件来映射 JavaBean 和数据库表的关系。代码如下:
<resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.resultmap.demo7.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="bookList" ofType="com.hxstrive.mybatis.resultmap.demo7.BookBean"> <id column="book_id" jdbcType="INTEGER" property="bookId" /> <result column="book_name" jdbcType="VARCHAR" property="bookName" /> <result column="price" jdbcType="FLOAT" property="price" /> <result column="content" jdbcType="VARCHAR" property="content" /> </collection> </resultMap>
上面 XML 代码是一个完整的结果映射,将 com.hxstrive.mybatis.resultmap.demo7.UserBean 映射成 RESULT_MAP,这样我们就可以在 <select> 标签的 resultMap 属性中使用。<collection> 标签实现用户和书籍之间的关联映射,其中:
property:用来指定需要映射的 JavaBean 的集合属性名,如:bookList
ofType:该属性指定了 property 指定的 JavaBean 属性的 Java 类型,例如:com.hxstrive.mybatis.resultmap.demo7.BookBean
<collection> 标签内部的 <id>、<result> 标签用法和 <resultMap>、<association> 下面的 <id>、<result> 标签一样,这里将不再赘述。
(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\demo7\UserMapper.xml" /> </mappers> </configuration>
(2)UserBean 和 BookBean 代码如下:
a、UserBean.java
package com.hxstrive.mybatis.resultmap.demo7; import java.util.List; public class UserBean { private Integer userId; private String name; private String sex; private Integer age; private List<BookBean> bookList; public UserBean(Integer userId, String name) { this.userId = userId; this.name = name; } // 忽略 getter 和 setter @Override public String toString() { StringBuilder books = new StringBuilder(); for(BookBean bookBean : bookList) { books.append("\n\t").append(bookBean.toString()); } return "UserBean{" + "userId=" + userId + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + "} " + books; } }
b、BookBean.java
package com.hxstrive.mybatis.resultmap.demo7; public class BookBean { private Integer bookId; private String bookName; private Float price; private String content; // 忽略 getter 和 setter @Override public String toString() { return "BookBean{" + "bookId=" + bookId + ", bookName='" + bookName + '\'' + ", price=" + price + ", content='" + content + '\'' + '}'; } }
(3)Mapper 接口文件 UserMapper.java 代码如下:
package com.hxstrive.mybatis.resultmap.demo7; 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.demo7.UserMapper"> <resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.resultmap.demo7.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="bookList" ofType="com.hxstrive.mybatis.resultmap.demo7.BookBean"> <id column="book_id" jdbcType="INTEGER" property="bookId" /> <result column="book_name" jdbcType="VARCHAR" property="bookName" /> <result column="price" jdbcType="FLOAT" property="price" /> <result column="content" jdbcType="VARCHAR" property="content" /> </collection> </resultMap> <select id="findAll" resultMap="RESULT_MAP"> select u.`user_id`, u.`name`, u.`sex`, u.`age`, b.book_id, b.book_name, b.price, b.content from `user` u join `user_book` ub on u.user_id=ub.user_id join `book` b on b.book_id=ub.book_id </select> </mapper>
(5)客户端代码如下:
package com.hxstrive.mybatis.resultmap.demo7; 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 ResultMapDemo7 { public static void main(String[] args) throws Exception { // 获取 Mapper 对象 String cfgName = "com/hxstrive/mybatis/resultmap/demo7/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); } } }