Mybatis批量更新數(shù)據(jù)庫錯誤問題
問題
記錄一次使用Mybatis批量更新數(shù)據(jù)庫的錯誤,錯誤信息,
Error updating database. Cause: org.postgresql.util.PSQLException: 錯誤: 字段 "update_time" 的類型為 timestamp without time zone, 但表達(dá)式的類型為 text 建議:你需要重寫或轉(zhuǎn)換表達(dá)式 位置:391
如下圖,說我有一個字段是timestamp類型,但是我表達(dá)式計(jì)算出來的是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>
關(guān)于Mybatis批量更新對象,參考下面這篇文章:
- 老實(shí)說,我也不知道為什么,之前用都沒問題。
- 我推測是不是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
就是說,我對象不傳這個字段了,直接使用數(shù)據(jù)庫自帶的now()方法來更新,反正都是獲取當(dāng)前時間。
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
apollo與springboot集成實(shí)現(xiàn)動態(tài)刷新配置的教程詳解
這篇文章主要介紹了apollo與springboot集成實(shí)現(xiàn)動態(tài)刷新配置,本文分步驟給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
java公眾平臺通用接口工具類HttpConnectUtil實(shí)例代碼
下面小編就為大家分享一篇java公眾平臺通用接口工具類HttpConnectUtil實(shí)例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01
Java中List的contains()方法的使用小結(jié)
List?的?contains()?方法用于檢查列表中是否包含指定的元素,借助equals()方法進(jìn)行判斷,下面就來介紹Java中List的contains()方法的使用小結(jié),感興趣的可以了解一下2025-04-04
Spring?AI?+?混元帶你實(shí)現(xiàn)企業(yè)級穩(wěn)定可部署的AI業(yè)務(wù)智能體
我們深入探討了Spring?AI在智能體構(gòu)建中的實(shí)際應(yīng)用,特別是在企業(yè)環(huán)境中的價值與效能,通過逐步實(shí)現(xiàn)一個本地部署的智能體解決方案,我們不僅展示了Spring?AI的靈活性與易用性,還強(qiáng)調(diào)了它在推動AI技術(shù)與業(yè)務(wù)深度融合方面的潛力,感興趣的朋友一起看看吧2024-11-11
Springboot2 session設(shè)置超時時間無效的解決
這篇文章主要介紹了Springboot2 session設(shè)置超時時間無效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07

