MaBatis之Mapper.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="dao.CategoryMapper">
  <resultMap id="BaseResultMap" type="domain.Category">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <!-- 这个关联属性所对应的sql是查询该类别下的所有图书信息 -->
    <!-- 定义关联属性 ofType集合元素的类型 column对应的列名就是外键 这里对应的Category的id
         该属性对应查询的sql语句利用select标签将设置好的select语句的id属性值放入
         collection对应的是一对多关联关系
         fetchType这里填的是lazy也就是懒加载
      -->
    <collection property="books" javaType="list" ofType="Book" column="id" select="selectBooks"
    fetchType="lazy">
    </collection>
  </resultMap>

  <resultMap id="bookResultMap" type="domain.Book">
    <id column="id" property="id"/>
    <result column="title" property="title"/>
    <result column="author" property="author"/>
    <result column="isbn" property="isbn"/>
  </resultMap>

  <sql id="Base_Column_List">
    id, `name`
  </sql>

  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from category
    where id = #{id,jdbcType=INTEGER}
  </select>
 
 <!-- 已知目录编号,查询它所拥有的图书 -->
  <select id="selectBooks" resultMap="bookResultMap" parameterType="int">
    select id,title,author,isbn from book where category_id = #{catId}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from category
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" keyColumn="id" keyProperty="id" parameterType="domain.Category" useGeneratedKeys="true">
    insert into category (`name`)
    values (#{name,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="domain.Category" useGeneratedKeys="true">
    insert into category
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="name != null">
        `name`,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="domain.Category">
    update category
    <set>
      <if test="name != null">
        `name` = #{name,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="domain.Category">
    update category
    set `name` = #{name,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值