手记

MyBatis实现一对多和多对一的关系

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

package com.mybatis.domain;  
import java.util.List;  

import lombok.Data;  
@Data//注释(Person为单方)  
public class Person {  
    private String personid;  

    private String personname;  

    private String personaddress;  

    private String persontel;  
    //这个代表多方里面的内容(Orders)  
    private List<Orders> orders;  
    @Override  
    public String toString() {  
        return "Person [personid=" + personid + ", personname=" + personname  
                + ", personaddress=" + personaddress + ", persontel="  
                + persontel + ", orders=" + orders + "]";  
    }  
}  

订单实体

/** 
 * 订单实体 
 */  
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 + "}";  
    }  

}  

一对多实体配置: 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"/>  

        <!-- 一对多的关系 用collection-->  
        <!-- 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>  

多对一实体配置:

<?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"/>  

        <!-- 多对一的关系用association -->  
        <!-- 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>  

总配置: 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>  

测试文件

/** 
 * 测试一对多和多对一 
 */  
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());  
    }  
}
3人推荐
随时随地看视频
慕课网APP