近期工作中有用到了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 >=#{starttime} and rttime <=#{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 >=#{starttime} and rttime <=#{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文件对大于小于的字符需要转义 分别对应如下。
原符号 < <= > >= & ' "
替换符号 < <= > >= & ' "
<if test="'username' eq 'sss'"></if> test里面支持java.lang.String 的方法 。也可自己定义类来限制