Mybatis关系映射

一、什么是关联关系?

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

二、关联关系的分类

1.一对一

这个就好像中国人的身份证一样,每个身份证对应一个人

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;

利用 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>

Mapper层


 
@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>

测试

 
@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);
    }
}

2.一对多

Mapper层

@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>

测试

@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);
    }
}

4.多对多

提供三个表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;

Mapper层

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

Mapper文件

<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>

测试加结果

@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}}
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值