MyBatis(3)-关系映射

1.关系映射1:N
1)新建数据库表customer及orders表


customer表结构.png

MyBatis(3)-关系映射_第1张图片
orders表结构.png

2)创建实体类

package com.capgemini.entity;

import java.util.List;

/*
实体类,Customer
*/
public class Customer {

   public List orders;
   public Integer id;
   public String name;

   public List getOrders() {
       return orders;
   }

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

   public Integer getId() {
       return id;
   }

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

   public String getName() {
       return name;
   }

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

   @Override
   public String toString() {
       return "Customer{" +
               "orders=" + orders +
               ", id=" + id +
               ", name='" + name + '\'' +
               '}';
   }
}
package com.capgemini.entity;

/*
实体类Order
 */
public class Orders {
    private Integer id;
    private String sn;
    private String remark;

    public Integer getId() {
        return id;
    }

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

    public String getSn() {
        return sn;
    }

    public void setSn(String sn) {
        this.sn = sn;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }
}

3)增加映射文件


MyBatis(3)-关系映射_第2张图片
sqlMapperConfig中增加.png





    
        
        
    

    
    
    
        
        
        
            
            
            
        
    

    

4)测试类

package com.capgemini.test;

import com.capgemini.entity.Customer;
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.Test;

import java.io.IOException;

public class MyBatisTest {
    @Test
    public void test06() throws IOException {
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("sqlMapperConfig.xml"));
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Map map = new HashMap();
        map.put("customerName","charies");
        List customers = sqlSession.selectList("com.capgemini.mapper.CustomerMapper.find",map);
        for (Customer c:customers
             ) {
            System.out.println(c);
        }
    }
}

测试结果:


image.png

5)文件结构:


MyBatis(3)-关系映射_第3张图片
image.png

6)总结
对于1:N关系,在resultMap中增加属性进行配置;其中配置的是n所对应的表(实体类);其中extends对应的是1对应的表对应的集合元素;

你可能感兴趣的:(MyBatis(3)-关系映射)