目录
6、使用choose when then
1、mybatis xml中大于等于的写法
1、用了转义字符把>和<替换掉
如:WHERE 1 = 1 AND start_date <= CURRENT_DATE AND
< | < | 小于号 |
> | > | 大于号 |
& | & | 和 |
' | ’ | 单引号 |
" | " | 双引号 |
2、使用<![CDATA[ ]]>
<![CDATA[o.lft >= 1 and o.rgt <= 9 ]]>
2、运行时报参数错误
MyBites:Parameter 'stationId' not found. Available parameters are [2, 1, 0, param1, param2, param3]
在dao中是这样写的:
List<LaneEtcCount> getList( Long stationId, int begin, int end);
在xml配置文件中是这样写的:
<select id="getList" resultType="LaneEtcCount">
SELECT * FROM LANE_ETC_COUNT
WHERE STATIONID = #{stationId}
AND RECORDING_DATE BETWEEN #{begin} and #{end}
ORDER BY STATIONID,LANECODE,RECORDING_DATE
</select>
解决方法:dao层代码的参数加上@param
List<LaneEtcCount> getList(@Param("stationId") Long stationId,@Param("begin")intbegin,@Param("end")intend);
3、Mybatis自动生成key值
- 使用useGeneratedKeys和keyProperty返回主键值
如果数据库支持自增长主键字段(比如mysql、sql server)设置useGeneratedKeys=”true”和keyProperty,这样就可以插入主键id值。告 诉 MyBatis 使 用 JDBC 的 getGeneratedKeys 方法来取出由数据,
<insert id="save" useGeneratedKeys="true" keyProperty="id">
</insert>
- 插入数据的时候,使用selectkey返回主键值
在Oracle主键自增的环境下:
<insert id="add" parameterType="com">
<selectKey resultType="java.lang.Long" order="AFTER" keyProperty="id">
SELECT SEQ_SYS_.currval FROM sys.DUAL
</selectKey>
INSERT INTO SYS_ (....)
VALUES (....)
</insert>
<insert id="add" parameterType="com">
<selectKey resultType="java.lang.Long" order="AFTER" keyProperty="id">
SELECT SEQ_SYS_.currval FROM sys.DUAL
</selectKey>
INSERT INTO SYS_ (....)
VALUES (....)
</insert>
注意:这是使用sequence和触发器的方式,在这种方式下一定要使用AFTER,不然ID会自增两次,返回的id不正确。
第二种方式就是不用触发器,使用before获取nextval,然后insert id字段
4、使用where标签
不要在使用 where 1=1,使用where标签,只有在至少1个条件满足的时候才插入where语句,如果只有一个满足并且是and或者or开头,where标签会自动去掉and 或者or
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
5、返回map类型对象
查询sql后直接返回map
public List<Map<String, Object>> getMapRoadLine()
<select id="getMapRoadLine" resultType="java.util.HashMap">
6、使用<choose><when><otherwise>
相当于java中的if..else if...else,注意otherwise需要有
<choose>
<when test="order != null and order.trim() != ''">
order by ${order}
</when>
<otherwise>
order by con.start_pile_no;
</otherwise>
</choose>