mybatis 一对多

创建数据库表

创建人员信息的表,里面有两个字段:
id:主键
name:名称

CREATE TABLE `person` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NULL, PRIMARY KEY (`id`));

 

创建订单信息的表
id:主键
sno:订单编号

psId:员工id

CREATE TABLE `orders` ( `id` INT NOT NULL AUTO_INCREMENT, `sno` VARCHAR(45) NUL, `psId` VARCHAR(45) NULL, PRIMARY KEY (`id`));

 

创建类 Person 人员信息

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class Person implements Serializable {

private Long id;
private String name;
private List<Orders> orders;

public Long getId() {
return id;
}

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

public String getName() {
return name;
}

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

public List<Orders> getOrders() {
return orders;
}

public void setOrders(List<Orders> orders) {
this.orders = orders;
}

@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", orders=" + orders +
'}';
}
}

 

Orders  订单

import java.io.Serializable;

public class Orders implements Serializable {

private Long id;
private String sno;
private String psId;

public Long getId() {
return id;
}

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

public String getSno() {
return sno;
}

public void setSno(String sno) {
this.sno = sno;
}

public String getPsId() {
return psId;
}

public void setPsId(String psId) {
this.psId = psId;
}

@Override
public String toString() {
return "Orders{" +
"id=" + id +
", sno='" + sno + '\'' +
", psId='" + psId + '\'' +
'}';
}
}

 

person  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.test.dao.PersonDao">

<resultMap id="getOrders" type="com.test.bean.Person"> 

<!--Person中的基本属性--> <id column="id" property="id"/> 

<result column="name" property="name"/> 

<!--关联属性的映射关系-->

 <collection property="orders" ofType="com.test.bean.Order"> 

<id column="oid" property="id"/> 
<result column="psId" property="psId"/> 
<result column="sno" property="sno"/> 
</collection> </resultMap> 

<select id="selectOrderById" resultMap="getOrders"> 
SELECT t.id tid,t.name tname,p.id oid,p.sno sno FROM person t , order p WHERE t.id = p.tid and t.id=#{id} 

</select> 

</mapper>

 

需要注意的是 

 collection 标签中 property 属性对应 person类中的 字段  orders

id标签 column 不能和 resultMap 标签一样 

service 方法跟测试方法就不写过,主要是xml中的配置 <collection>标签

 

posted @ 2022-04-20 14:24  奋斗的渣渣  阅读(54)  评论(0编辑  收藏  举报