开发者

Mybatis批量更新数据库错误问题

目录
  • 问题
  • 分析&解决
  • 总结

问题

记录一次使用MyBATis批量更新数据库的错误,错误信息,

Error updating database. Cause: org.PostgreSQL.util.PSQLException: 错误: 字段 "update_time" 的类型为 timestamp without time zone, 但表达式的类型为 text 建议:你需要重写或转换表达式 位置:391

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

Mybatis批量更新数据库错误问题

分析&解决

JavaBean对象如下,updateTime是Date类型

import lombok.Data;

import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;

@Table(name = "tb_user")
@Data
public cl编程ass User implements Serializable {

    private Integer id;

    private String user编程name;

    private String password;

    private Date createTiem;

    private Date updateTime;
}

批量更新SQL如下

    <update id="updateBatch" parameterType="java.util.ArrayList">
        update tb_user
        set

        username php= 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}
            <c编程hoose>
                <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
        <forejavascriptach 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()方法来更新,反正都是获取当前时间。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜