序言:
最近又在使用mybatis作为dao层的框架,其实之前也一直在用mybtais,但中间隔了一点时间没用,现在用起来还有点不太习惯,这边,我大概记录下在使用过程中觉得常用的知识点,方便以后记忆。
小技巧:
<where>
标签的使用:
不吹不黑,感觉标签应该是最常用的标签了, 没得辩了吧。
那么为什么要使用where标签呢?我们看下这个例子。
select * from t_sys_user
where
<if test="username != null >
userName= #{userName})
</if>
<if test="nickname != null>
and nickName = #{nickName })
</if>
当参数 userName 和 nickName都不为null是,ok是没问题的,但如果userName 为null,nickName也为null 呢? 就会出现
select * from t_sys_user
where
这肯定报错的。
如何解决:
1 在where 后面添加一个 1=1(这是之前项目做得)。
2 使用where标签(mybatis已经提供给我们解决方案了,为什么不去使用呢?)
select * from t_sys_user
<where>
<if test="username != null >
and userName= #{userName})
</if>
<if test="nickname != null>
and nickName = #{nickName })
</if>
</where>
where 元素知道只有在一个以上的if条件有值的情况下才去插入“WHERE”子句。而且,若最后的内容是“AND”或“OR”开头的,where 元素自动加上或者删除AND OR 这种连接词。
- 高级映射 collection和assiocation
先给大家说一下这两个标签的使用场景:
往往出现现在一个实体类里面包含另外一个实体类。
遇到这种情况,可以有两种解决方案:
1新建实体类(最简单,不要动脑子)。
2在原有的实体类上加上需要的实体类集合。(mapper文件需要映射)
collection和assiocation使用方法差不多,所以我这边就使用collection(我只说使用方法,没说其他哦,其实这两者还有有点区别的)
<resultMap id="AccessRoleMap" type="com.deepbluebi.aip.system.bean.mybatis.AccessRoleBean">
<result column="role_name" property="roleName" jdbcType="VARCHAR"/>
<result column="role_code" property="roleCode" jdbcType="VARCHAR"/>
</resultMap>
<resultMap id="BaseResultMap" type="com.deepbluebi.aip.system.bean.mybatis.AuthorityLevelBean">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="authority_level_name" property="authorityLevelName" jdbcType="VARCHAR"/>
<result column="authority_level_remark" property="authorityLevelRemark" jdbcType="VARCHAR"/>
<result column="is_calendar" property="isCalendar" jdbcType="VARCHAR"/>
<result column="is_default" property="isDefault" jdbcType="VARCHAR"/>
<result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
<result column="create_user" property="createUser" jdbcType="VARCHAR"/>
<result column="last_modify_time" property="lastModifyTime" jdbcType="TIMESTAMP"/>
<result column="last_modify_user" property="lastModifyUser" jdbcType="VARCHAR"/>
<collection property="accessRoleBeans" ofType="com.deepbluebi.aip.system.bean.mybatis.AccessRoleBean"
resultMap="AccessRoleMap"/>
</resultMap>
区别:
collection:1对多(比如博客和评论,一篇博客可能会有多个评论,这就是1对多,当你需要博客实体类的时候,可以使用collection)。
assiocation: 多对一(比如博客和作者,一篇博客只可能是一个作者,但是一个作者可以有多个博客,所以当你需要这种博客实体类的时候,可以使用assiocation)。
- mybaits 模糊查询以及大于等于写法
就这样:
name LIKE CONCAT(CONCAT('%',#{name}),'%')
mybatis 中的大于小于不能直接写 >= 或者 <=
解决方案:
1 加上 <![CDATA[ ]]>
举例:
<![CDATA[ and aif.failure_time <= #{recordBean.endDate} ]]>
2 转化一下
failureTime <= #{endDate}
failureTime >= #{endDate}
- mybatis 返回主键
<insert id="save" parameterType="com.deepbluebi.aip.system.bean.mybatis.AuthorityLevelBean"
useGeneratedKeys="true" keyProperty="id">
useGeneratedKeys 参数只针对 insert 语句生效,默认为 false。当设置为 true 时,表示如果插入的表以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键返回。
keyProperty的值是对象的属性值不是数据库表中的字段名。
只需要加入useGeneratedKeys 和 keyProperty就ok了。