Mybatis批量更新數(shù)據(jù)庫錯誤問題
問題
記錄一次使用Mybatis批量更新數(shù)據(jù)庫的錯誤,錯誤信息,
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
就是說,我對象不傳這個字段了,直接使用數(shù)據(jù)庫自帶的now()方法來更新,反正都是獲取當前時間。
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
apollo與springboot集成實現(xiàn)動態(tài)刷新配置的教程詳解
這篇文章主要介紹了apollo與springboot集成實現(xiàn)動態(tài)刷新配置,本文分步驟給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
java公眾平臺通用接口工具類HttpConnectUtil實例代碼
下面小編就為大家分享一篇java公眾平臺通用接口工具類HttpConnectUtil實例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01
Spring?AI?+?混元帶你實現(xiàn)企業(yè)級穩(wěn)定可部署的AI業(yè)務智能體
我們深入探討了Spring?AI在智能體構建中的實際應用,特別是在企業(yè)環(huán)境中的價值與效能,通過逐步實現(xiàn)一個本地部署的智能體解決方案,我們不僅展示了Spring?AI的靈活性與易用性,還強調了它在推動AI技術與業(yè)務深度融合方面的潛力,感興趣的朋友一起看看吧2024-11-11
Springboot2 session設置超時時間無效的解決
這篇文章主要介紹了Springboot2 session設置超時時間無效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07

