mybatis关系映射之一对多和多对一

时间:2014-09-01 01:41:22   收藏:0   阅读:40297

一. 简介:

本实例使用顾客和订单的例子做说明: 一个顾客可以有多个订单, 一个订单只对应一个顾客


二. 例子:

1. 代码结构图:

bubuko.com,布布扣


2. 建表语句:

CREATE DATABASE test;  

USE test;

CREATE TABLE person(
  personId VARCHAR(36) PRIMARY KEY,
  personName VARCHAR(64),
  personAddress VARCHAR(128),
  personTel VARCHAR(11)
);

CREATE TABLE orders(
  orderId VARCHAR(36) PRIMARY KEY,
  orderNumber VARCHAR(20),
  orderPrice INT,
  pid VARCHAR(36)
);

INSERT INTO person VALUES('001', 'Jack', 'Wuhan', '1234567');
INSERT INTO orders VALUES('O_00001', '00001', 100, '001');
INSERT INTO orders VALUES('O_00002', '00002', 200, '001');

SELECT p.*, o.*
FROM person p 
  JOIN orders o ON (p.personId=o.pid)
WHERE p.personId = '001'

3. 顾客实体:

/**
 * 客户实体 
 */
public class Person {

	private String id;
	private String name;
	private String address;
	private String tel;
	
	private List<Order> orders;
	
	@Override
	public String toString() {
		return "{id: " + id + ", name: " + name + ", address: " + address + ", tel: " + tel + "}";
	}
}

4. 订单实体:

/**
 * 订单实体
 */
public class Order {

	private String id;
	private String number;
	private int price;
	
	private Person person; 
	
	@Override
	public String toString() {
		return "{id: " + id + ", number: " + number + ", price: " + price + "}";
	}

}


5. 一对多实体配置: Person.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zdp.domain.Person">

	<resultMap type="Person" id="personBean">
		<id column="personId" property="id"/>
		<result column="personName" property="name"/>
		<result column="personAddress" property="address"/>
		<result column="personTel" property="tel"/>
		
		<!-- 一对多的关系 -->
		<!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
		<collection property="orders" ofType="Order">
			<id column="orderId" property="id"/>
			<result column="orderNumber" property="number"/>
			<result column="orderPrice" property="price"/>
		</collection>
	</resultMap>
	
	<!-- 根据id查询Person, 关联将Orders查询出来 -->
	<select id="selectPersonById" parameterType="string" resultMap="personBean">
		select p.*, o.* from person p, orders o where p.personId  = o.pid and p.personId = #{id}
	</select>
	
</mapper>

6. 多对一实体配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zdp.domain.Order">
	<resultMap type="Order" id="orderBean">
		<id column="orderId" property="id"/>
		<result column="orderNumber" property="number"/>
		<result column="orderPrice" property="price"/>
		
		<!-- 多对一的关系 -->
		<!-- property: 指的是属性的值, javaType:指的是属性的类型-->
		<association property="person" javaType="Person">
			<id column="personId" property="id"/>
			<result column="personName" property="name"/>
			<result column="personAddress" property="address"/>
			<result column="personTel" property="tel"/>
		</association>
	</resultMap>
	
	<!-- 根据id查询Order, 关联将Person查询出来 -->
	<select id="selectOrderById" parameterType="string" resultMap="orderBean">
		select p.*, o.* from person p, orders o where p.personId  = o.pid and o.orderId = #{id}
	</select>
	
</mapper>

7. 总配置: sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<typeAliases>
		<typeAlias type="com.zdp.domain.Person" alias="Person"/>  
        <typeAlias type="com.zdp.domain.Order" alias="Order"/>  
	</typeAliases>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost/test" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<!-- 映射文件的位置 -->
		<mapper resource="com/zdp/domain/Person.xml" />
		<mapper resource="com/zdp/domain/Order.xml" />
	</mappers>
</configuration>

8. 测试文件:

/**
 * 测试一对多和多对一
 */
public class MybatisTest {

	private SqlSessionFactory ssf; 

	@Before
	public void initSF() throws Exception {
		String resource = "sqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		ssf = new SqlSessionFactoryBuilder().build(inputStream);
	}

	@Test//一对多关联查询
	public void selectPersonById()throws Exception{
		SqlSession session = ssf.openSession();
		Person person = session.selectOne("com.zdp.domain.Person.selectPersonById", "001");
		System.out.println(person.getOrders());
	}
	
	@Test//多对一关联查询
	public void selectOrderById()throws Exception{
		SqlSession session = ssf.openSession();
		Order order = session.selectOne("com.zdp.domain.Order.selectOrderById", "O_00001");
		System.out.println(order.getPerson().getName());
	}
}


评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!