天天看點

Mybatis關聯映射之關聯多個對象,即一對多(二)

已知條件已在上一篇關聯單個對象的文中寫明,這篇文章則繼續根據上篇的已知資料,實作Mybatis一對多的兩種關聯查詢方式

新增資料如下:

1、dao.UserDao.java(Mapper映射器)

package dao;
import entity.User;
public interface UserDao {
	//關聯多個對象
	public User findUserById1(String userId);//一條語句執行sql
	public User findUserById2(String userId);//兩條語句執行sql
}
           

2、UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
 
 <!-- namespace為命名空間,需與映射器全名一緻 -->
<mapper namespace="dao.UserDao">
	<!-- 使用一條sql語句來加載User和關聯的Book(關聯多個對象) -->
	<select id="findUserById1" parameterType="String" resultMap="userMap1">
		select *from cn_user u join cn_book b on(u.cn_user_id=b.cn_user_id)
			where u.cn_user_id=#{id}
	</select>
	<resultMap id="userMap1" type="entity.User">
		<!-- 定義cn_user字段的裝載,一定不能少寫 -->
		<id property="cn_user_id" column="cn_user_id" />
		<result property="cn_user_name" column="cn_user_name" />
		<result property="cn_user_password" column="cn_user_password" />
		<collection property="books" javaType="java.util.List" ofType="entity.Book">
			<id property="cn_book_id" column="cn_book_id" />
			<result property="cn_user_id" column="cn_user_id" />
			<result property="cn_book_name" column="cn_book_name" />
		</collection>
	</resultMap>
	
	
	<!-- 使用兩條sql語句來加載User和關聯的Book(關聯多個對象) -->
	<select id="findUserById2" parameterType="String" resultMap="userMap2">
		select *from cn_user where cn_user_id=#{id}
	</select>
	<resultMap id="userMap2" type="entity.User">
		<!-- 映射主鍵 -->
		<id property="cn_user_id" column="cn_user_id"/>
		<!-- 映射其他字段,此處可以選擇性指定其他屬性 -->
		<result property="cn_user_name" column="cn_user_name"/>
		<!-- 指定books屬性是一個List<Book>集合 -->
		<collection property="books" javaType="java.util.List" ofType="entity.Book"
			select="findBooks" column="cn_user_id" >
		</collection>
	</resultMap>
	<select id="findBooks" parameterType="String" resultType="entity.Book">
		select *from cn_book where cn_user_id=#{userId}
	</select>
</mapper>
           

3、測試類TestCase.java

package test;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import dao.UserDao;
import entity.User;

public class TestCase {
	private UserDao dao;
	private ApplicationContext ac;
	@Before
	public void init() {
		ac = new ClassPathXmlApplicationContext("spring-mybatis.xml");
		dao = ac.getBean("userDao", UserDao.class);
	}
	@Test
	public void test01() {
		User user = dao.findUserById1("使用者id");//一對多,使用一條sql查詢
		System.out.println(user);
	}
	@Test
	public void test02() {
		User user = dao.findUserById2("使用者id");//一對多,使用兩條sql查詢
		System.out.println(user);
	}
}
           

以上便是Mybatis關聯映射中的多個映射的兩種書寫情況,有不懂的可以評論或者私聊