Mybatis 一对多(OneToOne)关系映射

http://kinglixing.blog.51cto.com/3421535/709738

关于MyBatis一对多的设置如下:
1.创建数据库脚本
CREATE TABLE t_customer( 
  id int(10) not null auto_increment, 
  address varchar(120), 
  postcode varchar(6), 
  sex varchar(2), 
  cname varchar(24), 
  primary key(id) 
)charset="GB2312"; 

CREATE TABLE t_orders( 
  id int(10) not null auto_increment, 
  code varchar(24), 
  customer_id int(3) not null, 
  primary key(id) 
)charset="GB2312";

ALTER TABLE t_orders 
ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES t_customer(id)
-- t_orders.customer_id 参照 t_customer.id
 
2.创建实体类(POJO)
Customer.java
package com.lixing.ibatis.entity.onetomany; 

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

public class Customer implements Serializable{ 
  private static final long serialVersionUID = 451949797460417653L; 
  private int id; 
  private String address; 
  private String postcode; 
  private String sex; 
  private String cname; 
  private List<Orders> orders;   //一个Customer 对应N多个Orders

  public int getId() { 
    return id; 
  } 
  public void setId(int id) { 
    this.id = id; 
  } 
  public String getAddress() { 
    return address; 
  } 
  public void setAddress(String address) { 
    this.address = address; 
  } 
  public String getPostcode() { 
    return postcode; 
  } 
  public void setPostcode(String postcode) { 
    this.postcode = postcode; 
  } 
  public String getSex() { 
    return sex; 
  } 
  public void setSex(String sex) { 
    this.sex = sex; 
  } 
  public String getCname() { 
    return cname; 
  } 
  public void setCname(String cname) { 
    this.cname = cname; 
  } 
  public List<Orders> getOrders() { 
    return orders; 
  } 
  public void setOrders(List<Orders> orders) { 
    this.orders = orders; 
  } 
 
Orders.java
package com.lixing.ibatis.entity.onetomany; 

import java.io.Serializable; 

public class Orders implements Serializable { 
  private static final long serialVersionUID = 8215977396669780567L; 
  private int id; 
  private String code; 
  private int customerId; 
  private Customer customer;  //多个Orders对应一个Customer
    
  public int getId() { 
    return id; 
  } 

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

  public String getCode() { 
    return code; 
  } 

  public void setCode(String code) { 
    this.code = code; 
  } 

  public int getCustomerId() { 
    return customerId; 
  } 

  public void setCustomerId(int customerId) { 
    this.customerId = customerId; 
  } 

  public Customer getCustomer() { 
    return customer; 
  } 

  public void setCustomer(Customer customer) { 
    this.customer = customer; 
  } 
 
3.创建Mapper映射接口
CustomerMapper.java
package com.lixing.ibatis.onetomany.mapper; 

import com.lixing.ibatis.entity.onetomany.Customer; 

public interface CustomerMapper { 
  void insertCustomer(Customer customer); 
  Customer getCustomer(int id); 
 
OrdersMapper.java
package com.lixing.ibatis.onetomany.mapper; 

import java.util.List; 

import com.lixing.ibatis.entity.onetomany.Orders; 

public interface OrdersMapper { 
  void insertOrders(Orders orders); 
  List<Orders> getOrders(int id);    //根据id
  List<Orders> getOrdersById(int customerId);   //根据customerId获得N多个对象
 
4.创建Mapper XML配置文件
CustomerMapper.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.lixing.ibatis.onetomany.mapper.CustomerMapper"> 
  <parameterMap type="Customer" id="parameterCustomerMap"> 
    <parameter property="id"/> 
    <parameter property="address"/> 
    <parameter property="postcode"/> 
    <parameter property="sex"/> 
    <parameter property="cname"/>     
  </parameterMap> 
    
  <insert id="insertCustomer" parameterMap="parameterCustomerMap"> 
    <selectKey    keyProperty="id" resultType="int" order="AFTER"> 
      SELECT @@IDENTITY AS ID 
    </selectKey> 
    INSERT INTO t_customer(address,postcode,sex,cname) 
    VALUES(#{address},#{postcode},#{sex},#{cname}) 
  </insert>        
    
  <resultMap type="Customer" id="resultCustomerMap"> 
    <result property="id" column="id"/> 
    <result property="address" column="address"/> 
    <result property="postcode" column="postcode"/> 
    <result property="sex" column="sex"/> 
    <result property="cname" column="cname"/> 
    <collection property="orders" column="id" select="com.lixing.ibatis.onetomany.mapper.OrdersMapper.getOrdersById"/> 
  </resultMap> 
    
  <select id="getCustomer" resultMap="resultCustomerMap" parameterType="int"> 
    SELECT * 
    FROM t_customer 
    WHERE id=#{id} 
  </select>         
</mapper> 
OrderMapper.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.lixing.ibatis.onetomany.mapper.OrdersMapper"> 
  <parameterMap type="Orders" id="parameterOrdersMap"> 
    <parameter property="id"/> 
    <parameter property="code"/> 
    <parameter property="customerId"/> 
  </parameterMap> 
    
  <insert id="insertOrders"    parameterMap="parameterOrdersMap"> 
    <selectKey    keyProperty="id" resultType="int" order="AFTER"> 
      SELECT LAST_INSERT_ID() AS ID 
    </selectKey> 
    INSERT INTO t_orders(code,customer_id) 
    VALUES(#{code},#{customerId}) 
  </insert>    
    
  <resultMap type="Orders" id="ordersMap"> 
    <result property="id" column="id"/> 
    <result property="code" column="name"/> 
    <result property="customerId" column="customer_id"/> 
    <association property="customer" javaType="Customer" column="customer_id" select="com.lixing.ibatis.onetomany.mapper.CustomerMapper.getCustomer"/> 
  </resultMap>    
  <select id="getOrders" resultMap="ordersMap" parameterType="int"> 
    SELECT * FROM t_orders 
    WHERE id=#{id} 
  </select> 
    
  <select id="getOrdersById" resultMap="ordersMap" parameterType="int"> 
    SELECT * FROM t_orders 
    WHERE customer_id=#{customer_id} 
  </select> 
    
</mapper>    
 
5.mybatis-config.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> 
  <settings> 
    <!-- changes from the defaults for testing --> 
    <setting name="cacheEnabled" value="false" /> 
    <setting name="useGeneratedKeys" value="true" /> 
    <setting name="defaultExecutorType" value="REUSE" /> 
  </settings> 
    
  <typeAliases> 
    <typeAlias type="com.lixing.ibatis.entity.onetomany.Customer" alias="Customer"/> 
    <typeAlias type="com.lixing.ibatis.entity.onetomany.Orders" alias="Orders"/> 
     
  </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/test" /> 
        <property name="username" value="root" /> 
        <property name="password" value="7501857" /> 
      </dataSource> 
    </environment> 
  </environments> 
  <mappers> 
    <mapper resource="com/lixing/ibatis/onetomany/mapper/CustomerMapper.xml"/> 
    <mapper resource="com/lixing/ibatis/onetomany/mapper/OrdersMapper.xml"/> 
  </mappers> 
</configuration> 
 
6.创建测试类
package com.lixing.ibatis.test; 

import java.util.Iterator; 
import java.util.List; 

import org.apache.ibatis.session.SqlSession; 
import org.apache.ibatis.session.SqlSessionFactory; 
import org.junit.After; 
import org.junit.Before; 
import org.junit.Test; 

import com.lixing.ibatis.entity.onetomany.Customer; 
import com.lixing.ibatis.entity.onetomany.Orders; 
import com.lixing.ibatis.onetomany.mapper.CustomerMapper; 
import com.lixing.ibatis.onetomany.mapper.OrdersMapper; 
import com.lixing.ibatis.util.MyBatisUtil; 


public class OrdersMapperTest { 
  private SqlSessionFactory sqlSessionFactory=null; 
  private SqlSession session=null; 
    
  @Before 
  public void before(){ 
    sqlSessionFactory=MyBatisUtil.getInstance(); 
    session=sqlSessionFactory.openSession(); 
  } 
    
  @Test 
  public void testInsertOrders(){ 
    Orders orders=new Orders(); 
    orders.setCode("code__1"); 
    orders.setCustomerId(1); 
     
    OrdersMapper ordersMapper=session.getMapper(OrdersMapper.class); 
    ordersMapper.insertOrders(orders); 
    session.commit();     
  } 
    
  @Test 
  public void testInsertCustomerOneToMany(){ 
    Customer customer=new Customer(); 
    customer.setCname("Lixing5"); 
    customer.setPostcode("518105"); 
    customer.setSex("男"); 
    customer.setAddress("广东省深圳市5"); 
     
    CustomerMapper customerMapper=session.getMapper(CustomerMapper.class); 
    customerMapper.insertCustomer(customer); 
    System.out.println(customer.getId()); 
     
    Orders orders1=new Orders(); 
    orders1.setCode("code__5_1"); 
    orders1.setCustomerId(customer.getId()); 
     
    Orders orders2=new Orders(); 
    orders2.setCode("code__5_2"); 
    orders2.setCustomerId(customer.getId()); 
     
    Orders orders3=new Orders(); 
    orders3.setCode("code__5_3"); 
    orders3.setCustomerId(customer.getId()); 
     
    OrdersMapper ordersMapper=session.getMapper(OrdersMapper.class); 
    ordersMapper.insertOrders(orders1); 
    ordersMapper.insertOrders(orders2); 
    ordersMapper.insertOrders(orders3); 
     
    session.commit();    
  } 
    
     
  @Test 
  public void testGetOrdersManyToOne(){ 
    OrdersMapper ordersMapper=session.getMapper(OrdersMapper.class); 
    List<Orders> list=ordersMapper.getOrdersById(5); 
    for(int i=0;i<list.size();i++){ 
      Orders orders=list.get(i); 
      Customer customer=orders.getCustomer(); 
      System.out.println(orders.getId()+"\t"+orders.getCode()+"\t"+orders.getCustomerId()); 
      System.out.println("\t \t--:"+customer.getId()+"\t"+customer.getCname()); 
    }     
    session.commit(); 
  } 
    
    
  @Test 
  public void testGetCustomerOneToMany(){ 
    CustomerMapper customerMapper=session.getMapper(CustomerMapper.class); 
    Customer customer=customerMapper.getCustomer(5); 
    List<Orders> orders=customer.getOrders(); 
    System.out.println(customer.getId()+"\t"+customer.getCname()+"\t"+customer.getPostcode()+"\t"+customer.getAddress()); 
    for(int i=0;i<orders.size();i++){ 
      Orders order=orders.get(i); 
      System.out.println("\t \t --:"+order.getId()+"\t"+order.getCode()+"\t"+order.getCustomerId()); 
    } 
    session.commit(); 
  } 
    
  @After 
  public void after(){ 
    session.close(); 
  } 

相关推荐