0
点赞
收藏
分享

微信扫一扫

MyBatis之关联关系映射

全栈顾问 2022-04-01 阅读 49
java

一、什么是关联关系?

关联关系是指类之间的引用关系,如果类A与类B关联,那么类A将被定义成类B的属性。

二、关联关系的分类

1.一对一

2.一对多

2.1.首先创建两个表t_customer(客户表)和 t_order(订单表)

-- 一对多
-- 客户表(主表)
create table t_customer
(
  customer_id int primary key not null auto_increment,
  customer_name varchar(50) not null
);

-- 多对一
-- 订单表(从表)
create table t_order
(
  order_id int primary key not null auto_increment,
  order_no varchar(50) not null unique,
  cid int not null,
  foreign key(cid) references t_customer(customer_id)
);

-- 初始化代码
delete from t_order;
delete from t_customer;

-- 与mssql不一样,自动增长是可以赋值,也可以不赋值
insert into t_customer(customer_id,customer_name) values(1, 'zs');
insert into t_customer(customer_id,customer_name) values(2, 'ls');
insert into t_customer(customer_id,customer_name) values(3, 'ww');
insert into t_customer(customer_id,customer_name) values(4, 'xm');

insert into t_order(order_no,cid) values('P01',1);
insert into t_order(order_no,cid) values('P02',1);
insert into t_order(order_no,cid) values('P03',1);
insert into t_order(order_no,cid) values('P04',1);
insert into t_order(order_no,cid) values('P05',1);
insert into t_order(order_no,cid) values('P06',2);
insert into t_order(order_no,cid) values('P07',2);
insert into t_order(order_no,cid) values('P08',2);
insert into t_order(order_no,cid) values('P09',3);
insert into t_order(order_no,cid) values('P10',3);

SELECT * FROM t_customer;
SELECT * FROM t_order;

 2.2.利用ssm逆向生成工具,将我们所需要的表的对应的代码生成

  generatorConfig.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
    <!-- 引入配置文件 -->
    <properties resource="jdbc.properties"/>

    <!--指定数据库jdbc驱动jar包的位置-->
    <classPathEntry location="E:\repository\mvn-repository\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar"/>

    <!-- 一个数据库一个context -->
    <context id="infoGuardian">
        <!-- 注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
            <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
        </commentGenerator>

        <!-- jdbc连接 -->
        <jdbcConnection driverClass="${jdbc.driver}"
                        connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>

        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 01 指定javaBean生成的位置 -->
        <!-- targetPackage:指定生成的model生成所在的包名 -->
        <!-- targetProject:指定在该项目下所在的路径  -->
        <javaModelGenerator targetPackage="com.zking.ssm.book.model"
                            targetProject="src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
            <property name="trimStrings" value="false"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!-- 02 指定sql映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.zking.ssm.book.mapper"
                         targetProject="src/main/resources">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 03 生成XxxMapper接口 -->
        <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
        <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
        <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
        <javaClientGenerator targetPackage="com.zking.ssm.book.mapper"
                             targetProject="src/main/java" type="XMLMAPPER">
            <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 配置表信息 -->
        <!-- schema即为数据库名 -->
        <!-- tableName为对应的数据库表 -->
        <!-- domainObjectName是要生成的实体类 -->
        <!-- enable*ByExample是否生成 example类 -->
        <!--<table schema="" tableName="t_book" domainObjectName="Book"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--&lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;-->
            <!--&lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;-->
            <!--&lt;!&ndash; 指定列的java数据类型 &ndash;&gt;-->
            <!--&lt;!&ndash; <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;-->
        <!--</table>-->

        <table schema="" tableName="t_order" domainObjectName="Order"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
            <!-- 忽略列,不生成bean 字段 -->
            <!-- <ignoreColumn column="FRED" /> -->
            <!-- 指定列的java数据类型 -->
            <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> -->
        </table>
        <table schema="" tableName="t_customer" domainObjectName="Customer"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
            <!-- 忽略列,不生成bean 字段 -->
            <!-- <ignoreColumn column="FRED" /> -->
            <!-- 指定列的java数据类型 -->
            <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> -->
        </table>

    </context>
</generatorConfiguration>

 2.3.修改或创建生成的代码

  实体类:Customer.java

/**
 * 一对多
 */
public class Customer {
    private Integer customerId;
 
    private String customerName;
 
    private List<Order> orders;
 
    public List<Order> getOrders() {
        return orders;
    }
 
    public void setOrders(List<Order> orders) {
        this.orders = orders;
    }
 
    public Customer(Integer customerId, String customerName) {
        this.customerId = customerId;
        this.customerName = customerName;
    }
 
    public Customer() {
        super();
    }
 
    public Integer getCustomerId() {
        return customerId;
    }
 
    public void setCustomerId(Integer customerId) {
        this.customerId = customerId;
    }
 
    public String getCustomerName() {
        return customerName;
    }
 
    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }
 
 
    @Override
    public String toString() {
        return "Customer{" +
                "customerId=" + customerId +
                ", customerName='" + customerName + '\'' +
                ", orders=" + orders +
                '}';
    }
}

  Mapper层接口:CustomerMapper.java

package com.zking.ssm.book.mapper;

import com.zking.ssm.book.model.Customer;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface CustomerMapper {

    List<Customer> queryCustomer();

}

  OrderMapper.xml

<resultMap id="ManyToOne" type="com.zking.ssm.book.model.Order">
    <id property="orderId"   javaType="java.lang.Integer" column="order_Id" />
    <result property="orderNo" javaType="java.lang.String" column="order_No"/>
    <result property="orderId" javaType="java.lang.Integer" column="order_Id"/>
    <association property="customer" javaType="com.zking.ssm.book.model.Customer">
      <id  property="customerId" javaType="java.lang.Integer" column="customer_Id" />
      <result property="customerName" javaType="java.lang.String" column="customer_Name"/>
    </association>
  </resultMap>
 
<select id="queryOrderId" resultMap="ManyToOne">
      select * from t_customer c inner join t_order o on c.customer_id=o.cid
      where o.order_id=#{value}
</select>

2.4.测试

CustomerServiceImplTest.java


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class CustomerServiceImplTest{
    @Autowired
    private ICustomerService iCustomerService;
 
    @Test
    public void queryOrders() {
        List<Customer> orders = iCustomerService.queryOrders();
        orders.forEach(System.out::println);
    }
}
//输出: 一个客户对应多个订单
/*
Customer{customerId=1, customerName='zs', orders=[Order{orderId=1, orderNo='P01', cid=null, customer=null}, Order{orderId=2, orderNo='P02', cid=null, customer=null}, Order{orderId=3, orderNo='P03', cid=null, customer=null}, Order{orderId=4, orderNo='P04', cid=null, customer=null}, Order{orderId=5, orderNo='P05', cid=null, customer=null}]}
Customer{customerId=2, customerName='ls', orders=[Order{orderId=6, orderNo='P06', cid=null, customer=null}, Order{orderId=7, orderNo='P07', cid=null, customer=null}, Order{orderId=8, orderNo='P08', cid=null, customer=null}]}
Customer{customerId=3, customerName='ww', orders=[Order{orderId=9, orderNo='P09', cid=null, customer=null}, Order{orderId=10, orderNo='P10', cid=null, customer=null}]}
Customer{customerId=4, customerName='xm', orders=[]}
*/

3.多对一

  3.1.修改或创建生成的代码

   实体类:Order.java

/**
 * 多对一
 */
public class Order {
    private Integer orderId;
 
    private String orderNo;
 
    private Integer cid;
 
    private Customer customer;
 
    public Customer getCustomer() {
        return customer;
    }
 
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
 
    public Order(Integer orderId, String orderNo, Integer cid) {
        this.orderId = orderId;
        this.orderNo = orderNo;
        this.cid = cid;
    }
 
    public Order() {
        super();
    }
 
    public Integer getOrderId() {
        return orderId;
    }
 
    public void setOrderId(Integer orderId) {
        this.orderId = orderId;
    }
 
    public String getOrderNo() {
        return orderNo;
    }
 
    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }
 
    public Integer getCid() {
        return cid;
    }
 
    public void setCid(Integer cid) {
        this.cid = cid;
    }
 
 
    @Override
    public String toString() {
        return "Order{" +
                "orderId=" + orderId +
                ", orderNo='" + orderNo + '\'' +
                ", cid=" + cid +
                ", customer=" + customer +
                '}';
    }
}

 Mapper层接口: OrderMapper.java

@Repository
public interface OrderMapper {
    Order queryOrderId(Integer OrderId);
}

CustomerMapper.xml:

<resultMap id="oneToMany" type="com.zking.ssm.book.model.Customer">
    <id  property="customerId" javaType="java.lang.Integer" column="customer_Id" />
    <result property="customerName" javaType="java.lang.String" column="customer_Name"/>
    <collection property="orders" ofType="com.zking.ssm.book.model.Order">
      <id property="orderId"   javaType="java.lang.Integer" column="order_Id" />
      <result property="orderNo" javaType="java.lang.String" column="order_No"/>
      <result property="orderId" javaType="java.lang.Integer" column="order_Id"/>
    </collection>
</resultMap>
 
<select id="queryOrders" resultMap="oneToMany">
    select * from t_customer c left join t_order o on c.customer_id=o.cid
</select>

3.2测试 :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class OrderServiceImplTest{
    @Autowired
    private IOrderService iOrderService;
 
 
    @Test
    public void queryOrderId() {
        Order order = iOrderService.queryOrderId(3);
        System.out.println(order);
    }
}
//输出  多个订单对应一个客户
/*
Order{orderId=3, orderNo='P03', cid=null, customer=Customer{customerId=1, customerName='zs', orders=null}}
*/

4.多对多

 1.创建表

t_news(新闻表)

t_category(新闻类型表) 

t_news_category(桥接表)

-- 多对多
-- 主表
create table t_news
(
  news_id int primary key auto_increment,          -- 新闻ID:主鍵
  title varchar(50) not null                       -- 标题
);

-- 主表
create table t_category
(
  category_id int primary key auto_increment,      -- 类别编号:主鍵
  category_name varchar(50) not null               -- 类别名称
);

-- 桥接表,在关系型数据库中:多对多关系是无法直接映射的,
-- 必须将一个多对多关系转换成二个一对多关系才能进行映射
create table t_news_category
(
  id int primary key not null auto_increment,
  nid int not null,
  cid int not null,
  foreign key(nid) references t_news(news_id),
  foreign key(cid) references t_category(category_id)
);


insert into t_news(news_id,title) values(1,'110');
insert into t_news(news_id,title) values(2,'111');
insert into t_news(news_id,title) values(3,'112');
insert into t_news(news_id,title) values(4,'113');
insert into t_news(news_id,title) values(5,'114');
insert into t_news(news_id,title) values(6,'115');
insert into t_news(news_id,title) values(7,'116');
insert into t_news(news_id,title) values(8,'117');
insert into t_news(news_id,title) values(9,'118');


insert into t_category(category_id,category_name) values(1,'焦点');
insert into t_category(category_id,category_name) values(2,'国际');
insert into t_category(category_id,category_name) values(3,'社会');
insert into t_category(category_id,category_name) values(4,'房产');
insert into t_category(category_id,category_name) values(5,'财经');
insert into t_category(category_id,category_name) values(6,'娱乐');


insert into t_news_category(nid,cid) values(1,1);
insert into t_news_category(nid,cid) values(1,2);

insert into t_news_category(nid,cid) values(2,1);
insert into t_news_category(nid,cid) values(2,2);

insert into t_news_category(nid,cid) values(3,1);
insert into t_news_category(nid,cid) values(3,2);
insert into t_news_category(nid,cid) values(3,3);

insert into t_news_category(nid,cid) values(4,1);
insert into t_news_category(nid,cid) values(4,2);
insert into t_news_category(nid,cid) values(4,3);
insert into t_news_category(nid,cid) values(4,4);


SELECT * FROM t_news;
SELECT * FROM t_category;
SELECT * FROM t_news_category;

2、创建相应的实体类对象、mapper层接口和mapper文件 

实体类对象  

 News.java

public class News {
    private Integer newsId;
 
    private String title;
 
    private List<Category> categoryList;
 
    public List<Category> getCategoryList() {
        return categoryList;
    }
 
    public void setCategoryList(List<Category> categoryList) {
        this.categoryList = categoryList;
    }
 
    public News(Integer newsId, String title) {
        this.newsId = newsId;
        this.title = title;
    }
 
    public News() {
        super();
    }
 
    public Integer getNewsId() {
        return newsId;
    }
 
    public void setNewsId(Integer newsId) {
        this.newsId = newsId;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
 
 
    @Override
    public String toString() {
        return "News{" +
                "newsId=" + newsId +
                ", title='" + title + '\'' +
                ", categoryList=" + categoryList +
                '}';
    }
}

Category.java

public class Category {
    private Integer categoryId;
 
    private String categoryName;
 
    private List<News> newsList;
 
 
    public List<News> getNewsList() {
        return newsList;
    }
 
    public void setNewsList(List<News> newsList) {
        this.newsList = newsList;
    }
 
    public Category(Integer categoryId, String categoryName) {
        this.categoryId = categoryId;
        this.categoryName = categoryName;
    }
 
    public Category() {
        super();
    }
 
    public Integer getCategoryId() {
        return categoryId;
    }
 
    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }
 
    public String getCategoryName() {
        return categoryName;
    }
 
    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
 
    @Override
    public String toString() {
        return "Category{" +
                "categoryId=" + categoryId +
                ", categoryName='" + categoryName + '\'' +
                ", newsList=" + newsList +
                '}';
    }
}

News_Category.java

public class News_Category {
    private Integer id;
 
    private Integer nid;
 
    private Integer cid;
 
    private News news;
    private Category category;
 
    public News getNews() {
        return news;
    }
 
    public void setNews(News news) {
        this.news = news;
    }
 
    public Category getCategory() {
        return category;
    }
 
    public void setCategory(Category category) {
        this.category = category;
    }
 
    public News_Category(Integer id, Integer nid, Integer cid) {
        this.id = id;
        this.nid = nid;
        this.cid = cid;
    }
 
    public News_Category() {
        super();
    }
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public Integer getNid() {
        return nid;
    }
 
    public void setNid(Integer nid) {
        this.nid = nid;
    }
 
    public Integer getCid() {
        return cid;
    }
 
    public void setCid(Integer cid) {
        this.cid = cid;
    }
 
    @Override
    public String toString() {
        return "News_Category{" +
                "id=" + id +
                ", nid=" + nid +
                ", cid=" + cid +
                ", news=" + news +
                ", category=" + category +
                '}';
    }
}

mapper层接口:News_CategoryMappe

@Repository
public interface News_CategoryMapper {
    //根据新闻id查询
    List<News_Category> queryNewsToMany(Integer newsId);
    //根据类型id查询
    List<News_Category> queryCategoryToMany(Integer categoryId);
 
}

mapper文件:News_CategoryMapper.xml

<resultMap id="ManyToMany" type="com.zking.ssm.book.model.News_Category">
    <id property="id" javaType="java.lang.Integer" column="id"/>
    <result property="nid" javaType="java.lang.Integer" column="nid"/>
      <result property="cid"  javaType="java.lang.Integer" column="cid"/>
    <association property="news" javaType="com.zking.ssm.book.model.News">
      <id property="newsId" javaType="java.lang.Integer"  column="category_Id"/>
     <result property="title" javaType="java.lang.String" column="title"/>
    </association>
 
     <association property="category" javaType="com.zking.ssm.book.model.Category">
         <id property="categoryId" javaType="java.lang.Integer"  column="category_Id"/>
         <result property="categoryName" javaType="java.lang.String" column="category_Name"/>
     </association>
  </resultMap>
 
<select id="queryNewsToMany" resultMap="ManyToMany">
        select
        *
        from
        t_news_category nc left join t_news n on nc.nid=n.news_id
        left join t_category c on nc.cid =c.category_id where n.news_id=#{value}
  </select>
 
  <select id="queryCategoryToMany" resultMap="ManyToMany">
      select
      *
      from
      t_news_category nc left join t_news n on nc.nid=n.news_id
      left join t_category c on nc.cid =c.category_id where c.category_id=#{value}
  </select>


3、测试代码和结果

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml"})
public class News_CategoryServiceImplTest{
    @Autowired
    private INews_CategoryService iNews_categoryService;
 
    @Test
    public void queryNewsToMany() {
        List<News_Category> news = iNews_categoryService.queryNewsToMany(1);
        news.forEach(System.out::println);
    }
 
    @Test
    public void queryCategoryToMany() {
        List<News_Category> categorys = iNews_categoryService.queryCategoryToMany(1);
        categorys.forEach(System.out::println);
    }
}
//输出
/*
queryNewsToMany:
News_Category{id=1, nid=1, cid=1, news=News{newsId=1, title='110', categoryList=null}, category=Category{categoryId=1, categoryName='焦点', newsList=[News{newsId=1, title='110', categoryList=null}]}}
News_Category{id=2, nid=1, cid=2, news=News{newsId=2, title='110', categoryList=null}, category=Category{categoryId=2, categoryName='国际', newsList=[News{newsId=2, title='110', categoryList=null}]}}

queryCategoryToMany:
News_Category{id=1, nid=1, cid=1, news=News{newsId=1, title='110', categoryList=null}, category=Category{categoryId=1, categoryName='焦点', newsList=null}}
News_Category{id=3, nid=2, cid=1, news=News{newsId=1, title='111', categoryList=null}, category=Category{categoryId=1, categoryName='焦点', newsList=null}}
News_Category{id=5, nid=3, cid=1, news=News{newsId=1, title='112', categoryList=null}, category=Category{categoryId=1, categoryName='焦点', newsList=null}}
News_Category{id=8, nid=4, cid=1, news=News{newsId=1, title='113', categoryList=null}, category=Category{categoryId=1,categoryName='焦点', newsList=null}}
*/
举报

相关推荐

0 条评论