Mybatis批量更新數(shù)據(jù)庫錯(cuò)誤問題
問題
記錄一次使用Mybatis批量更新數(shù)據(jù)庫的錯(cuò)誤,錯(cuò)誤信息,
Error updating database. Cause: org.postgresql.util.PSQLException: 錯(cuò)誤: 字段 "update_time" 的類型為 timestamp without time zone, 但表達(dá)式的類型為 text 建議:你需要重寫或轉(zhuǎn)換表達(dá)式 位置:391
如下圖,說我有一個(gè)字段是timestamp類型,但是我表達(dá)式計(jì)算出來的是text類型

分析&解決
JavaBean對(duì)象如下,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批量更新對(duì)象,參考下面這篇文章:
Mybatis批量更新對(duì)象數(shù)據(jù)的兩種方法
- 老實(shí)說,我也不知道為什么,之前用都沒問題。
- 我推測(cè)是不是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
就是說,我對(duì)象不傳這個(gè)字段了,直接使用數(shù)據(jù)庫自帶的now()方法來更新,反正都是獲取當(dāng)前時(shí)間。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring Boot之內(nèi)嵌tomcat版本升級(jí)操作示例
這篇文章主要為大家介紹了Spring Boot之內(nèi)嵌tomcat版本升級(jí)操作示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
Spring-AOP 靜態(tài)正則表達(dá)式方法如何匹配切面
這篇文章主要介紹了Spring-AOP 靜態(tài)正則表達(dá)式方法如何匹配切面的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
Idea的Generate Sources無法生成QueryDSL問題及解決方法
這篇文章主要介紹了解決Idea的Generate Sources無法生成QueryDSL問題,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02

