关于mybatis使用的坑

近期工作中有用到了mybatis了  ,好久没用了。果然把之前踩过的坑又老老实实踩一遍,为了记住教训,这次先记录下来

首先需要知道的问题,mybatis返回的结果需要封装,项目中我一般都是直接写了javabean类,里面存着关于映射数据库的字段,

然后呢  要在mybatis的xml文件中映射返回结果集。 涉及到1V1 1Vn  nVn都需要有不同的处理方法。

我这次需要换不同的表来查,表之间又无关联。相当于单表查询,因此简单。要根据需求不同的换表名,其实也就是sql 语句表名是变量就行 这里注意,因为是表名,所以不能用#{xxx}。大家都知道#带有预编译的效果  所以用${xxx},这个作用是直接拼接到sql语句中的。

mybatis的resultMap是个十分强大的东西,你要查询的数据返回的结果可以用它来执行。下面上例子

 <resultMap id="BaseResultMap" type="com.xxx.xxx.bean.Pushbean"> 

   <id column="id"  property="id" />                              
    <result column="ptnum"  property="ptnum" />
    <result column="rttime"  property="rttime" />
    <result column="push_success"  property="pushSuccess" />
    <result column="push_fail"  property="pushFail" />

</resultMap> 

用到什么数据封装什么数据就好,这些用到的数据你都可以在sql语句中做设置 不需要返回全部数据,封装多累哦

例1

<select id="pushsuccess" parameterType="String" resultMap="BaseResultMap">
  select    id, ptnum, rttime, push_success, push_fail from ${proid} where         
  <if test="proid neq 's_push_min'">
 <if test="starttime eq endtime">rttime=#{starttime}</if>
  <if test="starttime neq endtime">rttime &gt;=#{starttime} and rttime &lt;=#{endtime}</if>
  </if></select>

<sql id="Base_Column_List">      ///这个可以预装sql  需要的时候可以引入十分灵活  以上面的数据为例子
    id, ptnum, rttime, push_success, push_fail

</sql>

例2

<select id="pushsuccess" parameterType="String" resultMap="BaseResultMap">
  select    <include refid="Base_Column_List" />  from ${proid} where         
  <if test="proid neq 's_push_min'">
 <if test="starttime eq endtime">rttime=#{starttime}</if>
  <if test="starttime neq endtime">rttime &gt;=#{starttime} and rttime &lt;=#{endtime}</if>
  </if></select>

还有就是mybatis使用OGNL表达式的

  • e1 or e2
  • e1 and e2
  • e1 == e2,   e1 eq e2
  • e1 != e2,      e1 neq e2
  • e1 lt e2:小于
  • e1 lte e2:小于等于,其他gt(大于),gte(大于等于)
  • e1 in e2
  • e1 not in e2
  • e1 + e2,e1 * e2,e1/e2,e1 - e2,e1%e2
  • !e,not e:非,求反
  • e.method(args)调用对象方法
  • e.property对象属性值
  • e1[ e2 ]按索引取值,List,数组和Map
  • @class@method(args)调用类的静态方法
  • @class@field调用类的静态字段值

 

还有就是由于是xml文件对大于小于的字符需要转义 分别对应如下。

原符号       <        <=      >       >=       &        '        "
替换符号    &lt;    &lt;=   &gt;    &gt;=   &amp;   &apos;  &quot;

<if test="'username' eq 'sss'"></if>   test里面支持java.lang.String 的方法 。也可自己定义类来限制

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值