Mybatis关联

Posted 旧城微冷

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis关联相关的知识,希望对你有一定的参考价值。

一、一对多关联关系

1.通过generatorConfig.xml中首先先用逆向生成工具生成t_hibernate_order、t_hibernate_order_item
这两张表对应的model与mapper

<table schema="" tableName="t_hibernate_order" domainObjectName="Order"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">

        </table>
        <table schema="" tableName="t_hibernate_order_item" domainObjectName="OrderItem"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">

        </table>
        <table schema="" tableName="t_hibernate_book" domainObjectName="Hbook"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">

        </table>
        <table schema="" tableName="t_hibernate_category" domainObjectName="Category"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">

        </table>
        <table schema="" tableName="t_hibernate_book_category" domainObjectName="HbookCategory"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">

        </table>

 

 

   OrderItemVo.java 

package com.jt.model.vo;

import com.jt.model.Orde;
import com.jt.model.OrdeItem;

public class OrderItemVo extends OrdeItem {
    private Orde orde;

    public Orde getOrde() {
        return orde;
    }

    public void setOrde(Orde orde) {
        this.orde = orde;
    }
}
CategoryVo.java
package com.jt.model.vo;

import com.jt.model.Category;
import com.jt.model.Hbook;

import java.util.ArrayList;
import java.util.List;


public class CategoryVo  extends Category {
    private List<Hbook> hbooks=new ArrayList<>();

    public List<Hbook> getHbooks() {
        return hbooks;
    }

    public void setHbooks(List<Hbook> hbooks) {
        this.hbooks = hbooks;
    }
}
HbookVo.java
package com.jt.model.vo;

import com.jt.model.Category;
import com.jt.model.Hbook;

import java.util.ArrayList;
import java.util.List;


public class HbookVo extends Hbook {
    private List<Category> categories=new ArrayList<>();


//    public List<Category> getCategories() {
//        return categories;
//    }
//
//    public void setCategories(List<Category> categories)
//    {
//        this.categories = categories;
//    }

    public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }
}

 

@Test
    public void selectByOrderItemId() {
        List<OrderItemVo> orderItemVos = oneToManyService.selectByOrderItemId(36);
        OrderItemVo orderItemVo=orderItemVos.get(0);
        System.out.println(orderItemVo);
        System.out.println(orderItemVo.getOrde());
    }

    @Test
    public void selectByOrderId() {
        List<OrderVo> orderVos = oneToManyService.selectByOrderId(8);
        OrderVo orderVo=orderVos.get(0);
//        System.out.println(orderVos.size());
        System.out.println(orderVo);
        for (OrdeItem orderItem : orderVo.getOrderItems()) {
            System.out.println(orderItem);
        }
    }

 

 

 

 

2、多对多关联关系

首先先用逆向生成工具生成t_hibernate_book、t_hibernate_book_category(可生成可不生成)、t_hibernate_category,这两张表对应的model与mapper
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="D:\\\\initpath\\\\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.jt.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.jt.mapper"
                         targetProject="src/main/java">
            <!-- 是否允许子包,即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.jt.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_hibernate_order" domainObjectName="Orde"
               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_hibernate_order_item" domainObjectName="OrdeItem"
               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_hibernate_book`" domainObjectName="Hbook"
               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_hibernate_category" domainObjectName="Category"
               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_hibernate_book_category" domainObjectName="HbookCategory"
               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>-->



    </context>
</generatorConfiguration>

 HBookMapper

 

package com.hxc.mapper;


import com.hxc.model.Hbook;
import com.hxc.model.vo.HbookVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface HbookMapper {
    int deleteByPrimaryKey(Integer bookId);

    int insert(Hbook record);

    int insertSelective(Hbook record);

    Hbook selectByPrimaryKey(Integer bookId);

    int updateByPrimaryKeySelective(Hbook record);

    int updateByPrimaryKey(Hbook record);

    HbookVo selectByBid(@Param("bid") Integer bid);
}

 HBookMapper.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.hxc.mapper.HbookMapper" >
  <resultMap id="BaseResultMap" type="com.jt.model.Hbook" >
    <constructor >
      <idArg column="book_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="book_name" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="price" jdbcType="REAL" javaType="java.lang.Float" />
    </constructor>
  </resultMap>

  <resultMap id="HbookVoMap" type="com.hxc.model.vo.HbookVo">
    <result property="bookId" column="book_id"></result>
    <result property="bookName" column="book_name"></result>
    <result property="price" column="price"></result>
    <!--    <result property="orderItems"></result>-->
    <collection property="categories" ofType="com.hxc.model.Category">
      <result property="categoryId" column="category_id"></result>
      <result property="categoryName" column="category_name"></result>
    </collection>
  </resultMap>

  <sql id="Base_Column_List" >
    book_id, book_name, price
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_hibernate_book
    where book_id = #{bookId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_hibernate_book
    where book_id = #{bookId,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.hxc.model.Hbook" >
    insert into t_hibernate_book (book_id, book_name, price
      )
    values (#{bookId,jdbcType=INTEGER}, #{bookName,jdbcType=VARCHAR}, #{price,jdbcType=REAL}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.hxc.model.Hbook" >
    insert into t_hibernate_book
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="bookId != null" >
        book_id,
      </if>
      <if test="bookName != null" >
        book_name,
      </if>
      <if test="price != null" >
        price,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="bookId != null" >
        #{bookId,jdbcType=INTEGER},
      </if>
      <if test="bookName != null" >
        #{bookName,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        #{price,jdbcType=REAL},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.hxc.model.Hbook" >
    update t_hibernate_book
    <set >
      <if test="bookName != null" >
        book_name = #{bookName,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        price = #{price,jdbcType=REAL},
      </if>
    </set>
    where book_id = #{bookId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.hxc.model.Hbook" >
    update t_hibernate_book
    set book_name = #{bookName,jdbcType=VARCHAR},
      price = #{price,jdbcType=REAL}
    where book_id = #{bookId,jdbcType=INTEGER}
  </update>


  <select id="selectByBid" resultMap="HbookVoMap" >
    select * from t_hibernate_book b,t_hibernate_book_category bc,t_hibernate_category c
    where b.book_id=bc.bid and bc.cid=c.category_id
    and b.book_id=#{bid}
  </select>
</mapper>

 HBookCategoryMapper

package com.hxc.mapper;

import com.hxc.model.HbookCategory;

public interface HbookCategoryMapper {
    int deleteByPrimaryKey(Integer bcid);

    int insert(HbookCategory record);

    int insertSelective(HbookCategory record);

    HbookCategory selectByPrimaryKey(Integer bcid);

    int updateByPrimaryKeySelective(HbookCategory record);

    int updateByPrimaryKey(HbookCategory record);
}

 

 

 HBookCategoryMapper.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.hxc.mapper.HbookCategoryMapper" >
  <resultMap id="BaseResultMap" type="com.hxc.model.HbookCategory" >
    <constructor >
      <idArg column="bcid" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="bid" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="cid" jdbcType="INTEGER" javaType="java.lang.Integer" />
    </constructor>
  </resultMap>
  <sql id="Base_Column_List" >
    bcid, bid, cid
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_hibernate_book_category
    where bcid = #{bcid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_hibernate_book_category
    where bcid = #{bcid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.jt.model.HbookCategory" >
    insert into t_hibernate_book_category (bcid, bid, cid
      )
    values (#{bcid,jdbcType=INTEGER}, #{bid,jdbcType=INTEGER}, #{cid,jdbcType=INTEGER}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.hxc.model.HbookCategory" >
    insert into t_hibernate_book_category
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="bcid != null" >
        bcid,
      </if>
      <if test="bid != null" >
        bid,
      </if>
      <if test="cid != null" >
        cid,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="bcid != null" >
        #{bcid,jdbcType=INTEGER},
      </if>
      <if test="bid != null" >
        #{bid,jdbcType=INTEGER},
      </if>
      <if test="cid != null" >
        #{cid,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.hxc.model.HbookCategory" >
    update t_hibernate_book_category
    <set >
      <if test="bid != null" >
        bid = #{bid,jdbcType=INTEGER},
      </if>
      <if test="cid != null" >
        cid = #{cid,jdbcType=INTEGER},
      </if>
    </set>
    where bcid = #{bcid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.hxc.model.HbookCategory" >
    update t_hibernate_book_category
    set bid = #{bid,jdbcType=INTEGER},
      cid = #{cid,jdbcType=INTEGER}
    where bcid = #{bcid,jdbcType=INTEGER}
  </update>
</mapper>

测试

@Autowired
    private ManyToManyService manyToManyService;

    @Test
    public void selectByBid() {
        HbookVo hbookVo = manyToManyService.selectByBid(8);
        System.out.println(hbookVo);
        for (Category category : hbookVo.getCategories()) {
            System.out.println(category);
        }
    }

    @Test
    public void selectByCid() {
        CategoryVo categoryVo=this.manyToManyService.selectByCid(8);
        System.out.println(categoryVo);
        for (Hbook hbook : categoryVo.getHbooks()) {
            System.out.println(hbook);
        }

 

 


    }

 

 

一、一对多关联关系

1.通过generatorConfig.xml中首先先用逆向生成工具生成t_hibernate_order、t_hibernate_order_item
这两张表对应的model与mapper

以上是关于Mybatis关联的主要内容,如果未能解决你的问题,请参考以下文章

mybatis第二天——大纲待更新

MyBatis关联查询,表字段相同,resultMap映射问题的解决办法

mybatis第二天

mybatis专题-----代码生成器关联查询缓存

mybatis 一对一关联 association 返回空值

mybatis关联查询,一对一,一对多