MyBatis关联查询——一对多查询

本文记录Java学习过程中遇到的MyBatis关联查询——一对多查询~

案例:查询所有用户信息及用户关联的订单信息。

注意:用户信息和订单信息为一对多关系。

示例代码(SQL语句):

SELECT
	u.id,
	u.username,
	u.birthday,
	u.sex,
	u.address,
	o.id oid,
	o.number,
	o.createtime,
	o.note
FROM
	`user` u
LEFT JOIN `order` o ON u.id = o.user_id

示例代码(User类):

public class User {
	private int id;
	private String username;
	private String sex;
	private Date birthday;
	private String address;

	private List<Order> ordes;
}

示例代码(UserMapper.xml):

<resultMap type="user" id="userOrderResultMap">
	<id property="id" column="id" />
	<result property="username" column="username" />
	<result property="birthday" column="birthday" />
	<result property="sex" column="sex" />
	<result property="address" column="address" />

	<!-- 配置一对多的关系 -->
	<collection property="orders" javaType="list" ofType="order">
		<!-- 配置主键,是关联Order的唯一标识 -->
		<id property="id" column="oid" />
		<result property="number" column="number" />
		<result property="createtime" column="createtime" />
		<result property="note" column="note" />
	</collection>
</resultMap>

<!-- 一对多关联,查询订单同时查询该用户下的订单 -->
<select id="queryUserOrder" resultMap="userOrderResultMap">
	SELECT
	u.id,
	u.username,
	u.birthday,
	u.sex,
	u.address,
	o.id oid,
	o.number,
	o.createtime,
	o.note
	FROM
	`user` u
	LEFT JOIN `order` o ON u.id = o.user_id
</select>

示例代码(UserMapper.java):

List<User> queryUserOrder();

示例代码(UserMapperTest.java):

@Test
public void testQueryUserOrder() {
	// mybatis和spring整合,整合之后,交给spring管理
	SqlSession sqlSession = this.sqlSessionFactory.openSession();
	// 创建Mapper接口的动态代理对象,整合之后,交给spring管理
	UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

	// 使用userMapper执行根据条件查询用户
	List<User> list = userMapper.queryUserOrder();

	for (User u : list) {
		System.out.println(u);
	}

	// mybatis和spring整合,整合之后,交给spring管理
	sqlSession.close();
}

标签: none