Mybatis批量更新数据库错误

19 阅读1分钟

问题:记录一次使用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_user
        set

        username = 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>
        end

        where
        <foreach collection="users" item="user" separator="or">
            id = #{user.id}
        </foreach>
    </update>

关于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()方法来更新,反正都是获取当前时间。

首次发布

hezhongying.blog.csdn.net/article/det…