Mybatis日常使用总结

目录

1、mybatis xml中大于等于的写法

2、运行时报参数错误

3、Mybatis自动生成key值

4、使用where标签

5、返回map类型对象

6、使用choose when then


1、mybatis xml中大于等于的写法

1、用了转义字符把>和<替换掉

如:WHERE 1 = 1 AND start_date  &lt;= CURRENT_DATE AND 

&lt;<小于号
&gt;>大于号
&amp;&
&apos;单引号
&quot;"双引号

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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值