Mapper.xml理解

最开始对myBatis也没有很深的理解,最近写了很多mapper代码,也看了一下MyBatis指南

myBatis.xml

1.<mapper namespace="com.dfire.soa.cash.config.mapper.BackupPrinterMapper">

按住ctrl键点击BackupPrinterMapper,就会进入到mapper中的BackupPrinterMapper中,由此可见在该xml中的namespace必须与对应mapper所在的路径完全一致。

2.<resultMap>是一个自己定义的返回结果集的map。里面一般包含了所有的属性

<resultMap id="BackupPrinterMap" type="com.dfire.soa.cash.config.bo.BackupPrinter">

<id column="id" jdbcType="VARCHAR" property="id"/>

<result column="origin_ip" jdbcType="VARCHAR" property="originIp"/>

</resultMap>

resultMap id是用于在select语句中resultMap使用的,type是对用与相应的实体

id是指在数据库中主键,其中colunm对应的是数据库中的字段,即column必须与数据库中字段名字一模一样,jdbcType是指对应的字段的属性,与对应实体中的属性相同,不一定与数据库中的一样,例如,time在数据库中可以是Date类型,在实体中则是Long,那么jdbcType 应为Long,jdbcType并不影响什么,可以不要,但如果写了,而传过来的值的类型不匹配时,是会报错的。property对应于实体中的属性,与实体中的属性必须一模一样。


3.<select>语句

 <select id="selectByPrimaryKey" parameterType="map" resultMap="BackupPrinterMap">
         select *
         from backup_printer
         where id = #{id} and entity_id = #{entityId} 
    </select>

首先id,这个名字可以随便起,但是一定要与对应的Mapper中的名字一样,因为mapper中是根据名字相同来xml中找相应的方法,如果名字不同,会报错。我以前就犯过这种错误,

 BackupPrinter selectByPrimaryKey(@Param("id") String id, @Param("entityId") String entityId);

然后说parameterType= “map”,这个并不是传进来的参数必须是map,而是当你有两个及以上的参数时,那么paramType就必须是map了,同时mapper文件中如果只有一个参数, 是这样写的BackupPrinter selectByPrimaryKey(String id),而当有两个参数时,必须要加上@Param


3<where>标签

 <select id="selectByPrimaryKey" parameterType="map" resultMap="BackupPrinterMap">
         select *
         from backup_printer
         where

    <if test = "null != id">

    and id = #{id}

    </if>

    <if test = "null != entityId">

     and entity_id = #{entityId}

   </if>

    </select>

同时会出现一个问题,当你传进来的参数都为空时,那么语句就变成了  select *  from backup_printerwhere 这样肯定会报错,那么这时候就可以用<where>标签了    select *  from backup_printer <where> ...</where>


4.当有多个条件时,而这些条件又不能确定是否为空,就可以用<if test>标签


5.<sql>标签的使用,当一个条件会被用到多次时。

  <sql id="baseQuery">

<where>

 <if test = "null != id">

    and id = #{id}

    </if>

    <if test = "null != entityId">

     and entity_id = #{entityId}

   </if>

</where>

   </sql>

在具体使用时,只需要用<inclue>引入即可

   select * from backup_printer  <include refid="baseQuery"/>



  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值