mybatis的常见问题
分页
分页经常会遇到的问题,就是< (小于)、>(大于) 的问题,这里提供2种方式
方式1:使用html替换符
<if test="startIndex !=null and startIndex !=''">
rn >${startIndex}
</if>
<if test="endIndex !=null and endIndex !=''">
rn <${endIndex}
</if>
方式2:使用cdata可以直接写SQL操作
<if test="startIndex !=null and startIndex !=''">
<![CDATA[ and rn <= ${startIndex} ]]>
</if>
<if test="endIndex !=null and endIndex !=''">
<![CDATA[ and rn <= ${endIndex} ]]>
</if>
Mapper.xml中的 # 与 $
#可以防止SQL注入 $不能防止
#的参数是带引号的 而$不带引号
使用#和$ 主要取决于 1 是否需要防止SQL注入 2 是否是字符串参数
时间段的处理方式
<if test="operateBeginDate!=null and operateBeginDate!='' and operateEndDate!=null and operateEndDate!=''">
<![CDATA[
and to_date(OPERATE_DATE, 'yyyy-mm-dd') between to_date(#{operateBeginDate}, 'yyyy-mm-dd')
and to_date(#{operateEndDate},'yyyy-mm-dd')
]]>
</if>
异常为:Mapped Statements collection does not contain value for后面是什么类什么方法之类的
错误原因有几种:
- mapper.xml中没有加入namespace
- mapper.xml中的方法和接口mapper的方法不对应
- mapper.xml没有加入到mybatis-config.xml中(即总的配置文件),例外:配置了mapper文件的包路径的除外
- mapper.xml文件名和所写的mapper名称不相同。
mybatis 的外键关联 ,查询父表
1.数据库增加字段关联 (可选)
add constraint FK_AREA foreign key (AREA)
references SYS_AREA (ID);
commit;
2. 首先生成VO 和 mapper.xml 在VO中添加对象字段
<association property="sysArea" column="BANK_AREA" javaType="model.Area" select="model.Area.selectByPrimaryKey" />
mybatis 的外键关联 ,查询子表
生成VO和mapper.xml 在VO中添加子对象集合(1对多情况)
<collection property="comments" javaType="ArrayList" column="id" ofType="Comment" select="getCommentsById"/>