您的位置:首页 > 汽车 > 新车 > Mybatis批量更新数据库错误

Mybatis批量更新数据库错误

2024/10/20 8:20:28 来源:https://blog.csdn.net/qq_42108331/article/details/140804668  浏览:    关键词:Mybatis批量更新数据库错误

问题:记录一次使用Mybatis批量更新数据库的错误,错误信息,Error updating database. Cause: org.postgresql.util.PSQLException: 错误: 字段 "update_time" 的类型为 timestamp without time zone, 但表达式的类型为 text 建议:你需要重写或转换表达式 位置:391

如下图,说我有一个字段是timestamp类型,但是我表达式计算出来的是text类型

在这里插入图片描述

分析&解决:JavaBean对象如下,updateTime是Date类型

import lombok.Data;import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;@Table(name = "tb_user")
@Data
public class User implements Serializable {private Integer id;private String username;private String password;private Date createTiem;private Date updateTime;
}

批量更新SQL如下

    <update id="updateBatch" parameterType="java.util.ArrayList">update tb_usersetusername = case<foreach collection="users" item="user">when id = #{user.id}<choose><when test="user.username != null and user.username != ''">then #{user.username}</when><otherwise>then username</otherwise></choose></foreach>end,password = case<foreach collection="users" item="user">when id = #{user.id}<choose><when test="user.password != null and user.password != ''">then #{user.password}</when><otherwise>then password</otherwise></choose></foreach>end,update_time = case<foreach collection="users" item="user">when id = #{user.id}<choose><when test="user.updateTime != null">then #{user.updateTime}</when><otherwise>then update_time</otherwise></choose></foreach>endwhere<foreach collection="users" item="user" separator="or">id = #{user.id}</foreach></update>

关于Mybatis批量更新对象,参考下面这篇文章:

  • Mybatis批量更新对象数据的两种方法

老实说,我也不知道为什么,之前用都没问题。我推测是不是postgres的原因,我之前用的是MySQL。找不出来原因,我使用了下面这种方式解决:

        update_time = case<foreach collection="users" item="user">when id = #{user.id}<choose><when test="true">then now()</when><otherwise>then update_time</otherwise></choose></foreach>end

就是说,我对象不传这个字段了,直接使用数据库自带的now()方法来更新,反正都是获取当前时间。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com