MyBatis一对多和多对一

在学习MyBatis3的过程中,文档上面一直在强调一个id的东西!在做这个实验的时候,也因为没有理解清楚id含义而导致一对多的“多”中也只有一条数据。id和result的唯一不同是id表示的结果将是当比较对象实例时用到的标识属性。这帮助来改进整体表现,特别是缓存和嵌入结果映射。所以不同数据的id应该唯一区别,不然导致数据**结果集只有一条数据。
一、表

order.jpg

person.jpg

二、实体
1.person


[java] view plain copy

package com.kerwin.mybatis.pojo;

import java.util.List;

public class Person {

private int id;  
private String name;  
private List<Orders> orderList;  

public int getId() {  
    return id;  
}  

public void setId(int id) {  
    this.id = id;  
}  

public String getName() {  
    return name;  
}  

public void setName(String name) {  
    this.name = name;  
}  

public List<Orders> getOrderList() {  
    return orderList;  
}  

public void setOrderList(List<Orders> orderList) {  
    this.orderList = orderList;  
}  

@Override  
public String toString() {  
    return "Person [id=" + id + ", name=" + name + "]";  
}  

public Person() {  
    super();  
    // TODO Auto-generated constructor stub  
}  

public Person(int id, String name, List<Orders> orderList) {  
    super();  
    this.id = id;  
    this.name = name;  
    this.orderList = orderList;  
}  

}

[java] view plain copy

package com.kerwin.mybatis.pojo;

import java.util.List;

public class Person {

private int id;  
private String name;  
private List<Orders> orderList;  

public int getId() {  
    return id;  
}  

public void setId(int id) {  
    this.id = id;  
}  

public String getName() {  
    return name;  
}  

public void setName(String name) {  
    this.name = name;  
}  

public List<Orders> getOrderList() {  
    return orderList;  
}  

public void setOrderList(List<Orders> orderList) {  
    this.orderList = orderList;  
}  

@Override  
public String toString() {  
    return "Person [id=" + id + ", name=" + name + "]";  
}  

public Person() {  
    super();  
    // TODO Auto-generated constructor stub  
}  

public Person(int id, String name, List<Orders> orderList) {  
    super();  
    this.id = id;  
    this.name = name;  
    this.orderList = orderList;  
}  

}

2.order


[java] view plain copy

package com.kerwin.mybatis.pojo;

public class Orders {
private int id;
private double price;
private Person person;

public Person getPerson() {  
    return person;  
}  

public void setPerson(Person person) {  
    this.person = person;  
}  

public int getId() {  
    return id;  
}  

public void setId(int id) {  
    this.id = id;  
}  



public double getPrice() {  
    return price;  
}  

public void setPrice(double price) {  
    this.price = price;  
}  


  

@Override  
public String toString() {  
    return "Orders [id=" + id + ", price=" + price + "]";  
}  

public Orders() {  
    super();  
    // TODO Auto-generated constructor stub  
}  

}

[java] view plain copy

package com.kerwin.mybatis.pojo;

public class Orders {
private int id;
private double price;
private Person person;

public Person getPerson() {  
    return person;  
}  

public void setPerson(Person person) {  
    this.person = person;  
}  

public int getId() {  
    return id;  
}  

public void setId(int id) {  
    this.id = id;  
}  



public double getPrice() {  
    return price;  
}  

public void setPrice(double price) {  
    this.price = price;  
}  


  

@Override  
public String toString() {  
    return "Orders [id=" + id + ", price=" + price + "]";  
}  

public Orders() {  
    super();  
    // TODO Auto-generated constructor stub  
}  

}

三、映射mapper文件
1. PersonMapper.xml


[html] view plain copy

<?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.kerwin.mybatis.pojo.Person">
<resultMap type="com.kerwin.mybatis.pojo.Person" id="personreSultMap">
<id column="p_id" property="id"/>
<result column="name" property="name"/>
<collection property="orderList" ofType="com.kerwin.mybatis.pojo.Orders" column="pid">
<id column="o_id" property="id"/>
<result column="price" property="price"/>
</collection>

</resultMap>  
  
<select id="selectPersonFetchOrder" parameterType="int" resultMap="personreSultMap" >  
    select p.*,o.* from person p,orders o where o.pid=p.p_id and p.p_id=#{id}  
</select>  

</mapper>

[html] view plain copy

<?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.kerwin.mybatis.pojo.Person">
<resultMap type="com.kerwin.mybatis.pojo.Person" id="personreSultMap">
<id column="p_id" property="id"/>
<result column="name" property="name"/>
<collection property="orderList" ofType="com.kerwin.mybatis.pojo.Orders" column="pid">
<id column="o_id" property="id"/>
<result column="price" property="price"/>
</collection>

</resultMap>  
  
<select id="selectPersonFetchOrder" parameterType="int" resultMap="personreSultMap" >  
    select p.*,o.* from person p,orders o where o.pid=p.p_id and p.p_id=#{id}  
</select>  

</mapper>

2. OrdersMapper.xml


[html] view plain copy

<?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.kerwin.mybatis.pojo.Orders">
<resultMap type="com.kerwin.mybatis.pojo.Orders" id="OrdersResultMap">
<id column="o_id" property="id"/>
<result column="price" property="price"/>
<association property="person" javaType="com.kerwin.mybatis.pojo.Person">
<id column="p_id" property="id"/>
<result column="name" property="name"/>
</association>
</resultMap>

<select id="selectOrdersFetchPerson" resultMap="OrdersResultMap">  
    select p.*,o.* from person p,orders o where o.pid=p.p_id and o.o_id=#{id}   
</select>  

</mapper>

[html] view plain copy

<?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.kerwin.mybatis.pojo.Orders">
<resultMap type="com.kerwin.mybatis.pojo.Orders" id="OrdersResultMap">
<id column="o_id" property="id"/>
<result column="price" property="price"/>
<association property="person" javaType="com.kerwin.mybatis.pojo.Person">
<id column="p_id" property="id"/>
<result column="name" property="name"/>
</association>
</resultMap>

<select id="selectOrdersFetchPerson" resultMap="OrdersResultMap">  
    select p.*,o.* from person p,orders o where o.pid=p.p_id and o.o_id=#{id}   
</select>  

</mapper>

3.sqlMapConfig.xml


[html] view plain copy

<?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.kerwin.mybatis.pojo.Author" alias="Author"/>
</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:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/kerwin/mybatis/pojo/AuthorMapper.xml"/>
<mapper resource="com/kerwin/mybatis/pojo/PostMapper.xml"/>
<mapper resource="com/kerwin/mybatis/pojo/PersonMapper.xml"/>
<mapper resource="com/kerwin/mybatis/pojo/OrdersMapper.xml"/>
</mappers>
</configuration>

[html] view plain copy

<?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.kerwin.mybatis.pojo.Author" alias="Author"/>
</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:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/kerwin/mybatis/pojo/AuthorMapper.xml"/>
<mapper resource="com/kerwin/mybatis/pojo/PostMapper.xml"/>
<mapper resource="com/kerwin/mybatis/pojo/PersonMapper.xml"/>
<mapper resource="com/kerwin/mybatis/pojo/OrdersMapper.xml"/>
</mappers>
</configuration>

四。测试类


[java] view plain copy

/**

*/
package com.kerwin.mybatis.test;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;

import com.kerwin.mybatis.pojo.Orders;
import com.kerwin.mybatis.pojo.Person;

/**

  • @author Administrator

*/
public class PersonAndOrderTest {

private static SqlSessionFactory sessionFactory;  
  
/** 
 * @throws java.lang.Exception 
 */  
@BeforeClass  
public static void setUpBeforeClass() throws Exception {  
    SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();  
    InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");  
    sessionFactory = factoryBuilder.build(inputStream);  

}  
  
//一对多,查询person(一)级联查询订单order(多)  
@Test  
public void testSelectPersonFetchOrder() throws Exception {  
    SqlSession session = sessionFactory.openSession();  
    Person person = session.selectOne("com.kerwin.mybatis.pojo.Person.selectPersonFetchOrder", 1);  
    System.out.println(person);  
    System.out.println(person.getOrderList().size());  
    for(Orders orders : person.getOrderList()){  
        System.out.println(orders);  
    }  
    session.close();  
}  
  
//多对一,查询订单order(多)级联查询person(一)  
@Test  
public void testSelectOrdersFetchPerson() throws Exception{  
    SqlSession session = sessionFactory.openSession();  
    Orders orders = session.selectOne("com.kerwin.mybatis.pojo.Orders.selectOrdersFetchPerson", 1);  
    System.out.println(orders);  
    System.out.println(orders.getPerson());  
    session.close();  
}  

}

[java] view plain copy

/**

*/
package com.kerwin.mybatis.test;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;

import com.kerwin.mybatis.pojo.Orders;
import com.kerwin.mybatis.pojo.Person;

/**

  • @author Administrator

*/
public class PersonAndOrderTest {

private static SqlSessionFactory sessionFactory;  
  
/** 
 * @throws java.lang.Exception 
 */  
@BeforeClass  
public static void setUpBeforeClass() throws Exception {  
    SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();  
    InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");  
    sessionFactory = factoryBuilder.build(inputStream);  

}  
  
//一对多,查询person(一)级联查询订单order(多)  
@Test  
public void testSelectPersonFetchOrder() throws Exception {  
    SqlSession session = sessionFactory.openSession();  
    Person person = session.selectOne("com.kerwin.mybatis.pojo.Person.selectPersonFetchOrder", 1);  
    System.out.println(person);  
    System.out.println(person.getOrderList().size());  
    for(Orders orders : person.getOrderList()){  
        System.out.println(orders);  
    }  
    session.close();  
}  
  
//多对一,查询订单order(多)级联查询person(一)  
@Test  
public void testSelectOrdersFetchPerson() throws Exception{  
    SqlSession session = sessionFactory.openSession();  
    Orders orders = session.selectOne("com.kerwin.mybatis.pojo.Orders.selectOrdersFetchPerson", 1);  
    System.out.println(orders);  
    System.out.println(orders.getPerson());  
    session.close();  
}  

}

五、测试结果
1.一对多,查询person(一)级联查询订单order(多)

一对多.jpg

**


2.多对一,查询订单order(多)级联查询person(一)
**

多对一.jpg

**


注意:两张表中的主键id字段名要唯一,例如不能都写id,不然的话,在一对多查询的时候就会出现:级联出来的订单项只有一条记录。我之前就是将两张表的主键id字段名都写为id,导致测试结果级联出来的多一直只有一条数据,具体如下:
**

ps.jpg

**

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,723评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,485评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,998评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,323评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,355评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,079评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,389评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,019评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,519评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,971评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,100评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,738评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,293评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,289评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,517评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,547评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,834评论 2 345

推荐阅读更多精彩内容