MyBatis的初步使用

1、批量更新

<update id="batchUpdate" parameterType="java.util.List">  
update test set test=${item.test}+1 where id in  
<foreach collection="list" item="item" index="index" open="(" close=")" separator=",">  
${item.id}  
</foreach>  
</update>  

不建议的几种做法:
1、foreach放在外层,就是执行多次update,多次打开数据库
2、case when操作,这个看起来跟上面放出来的sql差不多,都是只执行一次sql就达到了批量更新的目的,但是经测试,效率太慢,或许是我不会用

Mybatis批量更新配置(Mysql batch update)

2、#和$在foreach的使用

<update id="updateCardStatus">
    update ctcc set credit = 1 where md5 in
  <foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
            #{item,jdbcType=VARCHAR}
   </foreach>
</update>

以上是正确mybatis语句,功能是批量更新ctcc表中的credit字段等于1,当md5在foreach循环中的list值这个范围内。
关键点在于

#{item,jdbcType=VARCHAR}

好多人说foreach中应该用$而不是#号,解释是$的参数直接输出,#的参数会被替换为?,然后传入参数值执行。
但这里我使用美元符号后却报错:

Cause: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Illegal double ‘002344e1860’ value found during parsing
; SQL []; Data truncation: Illegal double ‘002344e1860’ value found during parsing; nested exception is com.mysql.jdbc.MysqlDataTruncation: Data truncation: Illegal double ‘002344e1860’ value found during parsing

Mybatis foreach 批量操作

基于mysql对mybatis中的foreach进行深入研究

3、没有查询结果

 <select id="queryId" resultType="int">
        select IFNULL(MAX(mid),-1) as mid from id_config where operator = #{operator} order by id desc limit 1
</select>

核心就是IFNULL函数的使用,如果查询不到结果就为-1,或者其他指定的值。

使用MyBatis查询 返回类型为int,但是当查询结果为空NULL,报异常的解决方法

4、resultType和resultMap

正常情况下我会使用resultType,包括select insert update等语句,因为不管返回的是什么,比如返回一个int值,那么resultType=’int’,如果返回一个集合,那么resultType=’com.xm.po.AoPo’,注意这里需要使用到包名,也可以不加这个属性。
而resulttype的使用情况,个人认为是在查询返回的结果中没有与之相应的实体类,所以需要手动构造一个map来装载查询到的结果,类似这样

<resultMap id="userResultMap" type="User">
  <id property="id" column="user_id" />
  <result property="username" column="username"/>
  <result property="password" column="password"/>
</resultMap>

mybatis中resultType和resultMap使用时的区别

扫描二维码关注公众号,回复: 1585401 查看本文章

5、项目部署

将项目打成war包并用tomcat部署的方法,步骤及注意点
Unsupported major.minor version 52.0解决办法
[tomcat7源码学习]初始化之catalina.home和catalina.base(转)
Tomcat For Linux 的安装与配置详解
实时查看linux下tomcat运行日志

6、添加测试用例

https://blog.csdn.net/a86261566/article/details/50459487
http://www.51testing.com/html/61/n-3714961.html

猜你喜欢

转载自blog.csdn.net/diyangxia/article/details/80510320