Mybatis中对象映射关联之collection使用

本文详细介绍了MyBatis框架中如何实现关联映射,包括单对一(association)和一对多(collection)的关系处理,并通过具体示例展示了嵌套结果与嵌套查询的应用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考博文:
MyBatis中映射器之结果映射详解
MyBatis中对象映射关联之association使用实践

写在前言

  • one to one - association ;
    //单对一,使用association

  • one to many - collection ;
    //单对多,使用collection

  • Nested results - column is not necessary ,javaType is necessary !
    //使用嵌套结果,column 不是必需的,但是JavaType是必需的;

  • nested queries - column is necessary ,javaType is not necessary !
    //使用嵌套查询,column是必需的,JavaType不是必须的,子查询自定义resultType即可!!

表结构:

t_student 表拥有属性 class_id 对应 t_class表 t_id

这里写图片描述

【1】更改Classes,添加属性

Classes模型中包括多个Student:

public class Classes {

	private int id;
	private String name;
	private Teacher teacher;
	private List<Student> list;
	...
}

【2】嵌套结果-获取Classes,Teacher and list

下面实例讲关联都写在了getClass4Map结果映射中,其实association与collection的结果映射可以单独拎出来。

 <select id="getClass4" parameterType="int" resultMap="getClass4Map">
 	select * from t_class c,t_student s ,t_teacher where c.c_id = s.class_id and c.t_id = t_teacher.t_id and c.c_id = #{id}
 </select>
 
 <resultMap type="Classes" id="getClass4Map">
 	<result property="id" column="c_id" javaType="int" jdbcType="INTEGER"/>
 	<result property="name" column="c_name" javaType="string" jdbcType="VARCHAR"/>
 	

 	<association property="teacher"  column="t_id"  javaType="Teacher" >
 		<id property="id" column="t_id"  javaType="int" jdbcType="INTEGER"/>
 		<result property="name" column="t_name"  javaType="string" jdbcType="VARCHAR"/>
 	</association>
 	
 	<collection property="list" ofType="Student" >
 		<result property="id" column="s_id" javaType="int" jdbcType="INTEGER"/>
 		<result property="name" column="s_name" javaType="string" jdbcType="VARCHAR"/>
 	</collection>
 </resultMap>

【3】嵌套查询–获取Classes,Teacher and list

执行查询getClass5时,将会级联查询getTeacher和getStudent。

	 <select id="getClass5" parameterType="int" resultMap="getClass5Map">
	 	select * from t_class c where c.c_id = #{id}
	 </select>
	
	<select id="getTeacher" parameterType="int" resultType="Teacher">
		select t_id id,t_name name from t_teacher where t_id = #{id}
	</select>	 

	 <select id="getStudent" parameterType="int" resultType="Student">
	 	select s_id id,s_name name from t_student t where t.class_id = #{id}
	 </select>
	 
	 <resultMap type="Classes" id="getClass5Map">
	 	<result property="id" column="c_id" javaType="int" jdbcType="INTEGER"/>
	 	<result property="name" column="c_name" javaType="string" jdbcType="VARCHAR"/>

		<!--  here,column is necessary !!! 有属性select = getTeacher-->
	 	<association property="teacher" column="t_id" javaType="Teacher" select="getTeacher">
	 	</association>
	 	
	 	<!-- here,column is necessary !!! 有属性select = getStudent -->
	 	<collection  property="list"  ofType="Student"  select="getStudent"  column="c_id">
	 	</collection>
		<!-- pay attention to the Query condition of SQL statement  t.class_id = #{id}  not t.s_id = #{id} !!-->
	 </resultMap>

【4】代码测试

获取SqlSessionFactory的工具类:

public static SqlSessionFactory getFactory(){
		/* flow the src dir*/
		String resource = "mybatis.xml";
		/*MybatisUtils.class.getResourceAsStream(resource)----- it's wrong !!!!
		 * please distinguish the two up and down 
		 * */
		InputStream inputStream = MybatisUtils.class.getClassLoader().getResourceAsStream(resource);
		
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
		
		
		return factory;
	}

测试方法

@Test
public void testSelect4(){
	/*set auto commit ,which equals to the above*/
	SqlSession session = MybatisUtils.getFactory().openSession(true);
	
	String statement = "com.web.mapper.classMapper.getClass4";
	/*return the effect rows*/
	Classes classes = session.selectOne(statement, 1);
	Teacher teacher = classes.getTeacher();
	List<Student> list = classes.getList();
	System.out.println("result.."+classes+','+classes.getClass());
	System.out.println(teacher);
	System.out.println(list);
}

result as follows :

result..Classes [id=1, list=[Student [id=1, name=stu1], Student [id=2, name=stu2], Student [id=3, name=stu3]], name=计算机, teacher=Teacher [id=1, name=李明]],class com.web.model.Classes
Teacher [id=1, name=李明]
[Student [id=1, name=stu1], Student [id=2, name=stu2], Student [id=3, name=stu3]]
<think>嗯,用户问的是MyBatis中如何使用collection标签映射一个Integer数组。首先,我需要回忆一下MyBatis的结果映射机制。记得在MyBatis中,resultMap用来处理数据库结果集到Java对象映射,而collection标签通常用于处理一对的关系,比如一个对象中包含另一个对象的集合。 但这里用户提到的是Integer数组,也就是基本数据类型的包装类数组,不是自定义对象。这时候,可能需要确认collection标签是否支持基本类型的集合映射。根据之前的经验,collection的property属性对应Java对象的属性名,ofType指定集合中元素的类型。如果是Integer数组的话,ofType应该是java.lang.Integer。 接下来,我需要想一个示例场景。比如,假设有一个用户表,每个用户有个角色ID,这些角色ID存储在另一个表中,通过用户ID关联。那么查询用户的时候,需要将角色ID的数组映射到User对象的roleIds属性上,这里roleIds是一个Integer数组。 在XML映射文件中,需要编写一个resultMap,其中包含一个collection标签,property设为"roleIds",ofType设为"int"或者"java.lang.Integer"。然后,在select语句中使用这个resultMap,并通过JOIN语句连接用户表和角色表,获取对应的角色ID。 不过,要注意的是,如果直接使用collection标签,MyBatis可能会期望有一个嵌套的结果映射,但这里只需要简单的值,所以可能不需要复杂的配置。可能需要在collection标签中使用column属性指定从结果集中获取的列名,比如role_id,然后MyBatis会自动将其转换为Integer数组。 另外,还要考虑查询是否会返回行数据,比如每个用户有行记录,每个记录对应一个角色ID。这时候,MyBatis的集合映射会自动将个行中的role_id收集到数组中。可能需要使用groupBy属性来根据用户ID分组,确保每个用户的数据被正确聚合。 最后,测试这个配置是否有效,确保查询结果能正确映射到User对象的roleIds数组里。如果有问题,可能需要检查ofType是否正确,或者是否有其他配置错误,比如列名不匹配等。</think>在MyBatis使用`<collection>`标签映射Integer数组时,需要通过结果集映射实现一对关系的数据绑定。以下是具体实现步骤: ### 1. 实体类定义 ```java public class User { private Integer userId; private Integer[] roleIds; // 需要映射的Integer数组 // getters/setters } ``` ### 2. Mapper XML配置 ```xml <resultMap id="userResultMap" type="User"> <id property="userId" column="user_id"/> <!-- 集合映射需要指定ofType --> <collection property="roleIds" ofType="java.lang.Integer"> <result column="role_id"/> </collection> </resultMap> <select id="selectUserWithRoles" resultMap="userResultMap"> SELECT u.user_id, r.role_id FROM users u LEFT JOIN user_roles r ON u.user_id = r.user_id WHERE u.user_id = #{userId} </select> ``` ### 3. 查询结果处理 当查询返回行数据时,MyBatis会自动将`role_id`字段值收集到Integer数组中。例如查询结果: ``` user_id | role_id 1 | 101 1 | 102 ``` 最终会映射为`User.roleIds = [101, 102]` ### 4. 注意事项 - 必须指定`ofType="java.lang.Integer"`声明集合元素类型[^1] - 嵌套查询方式需要额外配置`select`属性(本例为直接连接查询) - 数组属性需要初始化空数组避免NPE[^2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流烟默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值