亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

H2 - 當 Persistable<ID> isNewObject 設置為 true 時

H2 - 當 Persistable<ID> isNewObject 設置為 true 時

catspeake 2021-07-02 10:03:30
我在 Java Spring Boot 應用程序中使用 H2 作為測試數據庫,但是當我想在嘗試插入重復的 ID/PK 時捕獲“重復鍵”異常時,H2 不會拋出任何內容。有了郵遞員,一切都很好,我就是無法通過測試。真正的數據庫是 PostgreSQL,當我與 Postman 集成測試時,它確實拋出異常。但是在單元測試時我認為沒有必要加載真正的DB所以我選擇了H2。H2配置:spring.datasource.url=jdbc:h2:mem:tesdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;mode=MySQLspring.datasource.driverClassName=org.h2.Driverspring.datasource.username=saspring.datasource.password=spring.datasource.testWhileIdle=truespring.datasource.validationQuery=SELECT 1spring.jpa.datasource.show-sql=truespring.h2.console.enabled=true # if you need console豆定義:@Entity@Data@JsonComponent@Table(name="bin_info")public class BinInfo implements Serializable, Persistable<String>{ //with Persistable we can check ID duplicate    @Id    @Size(min=6, max=8)    @Column(name="bin")    @JsonProperty("bin")    private String bin;    ...    /**     * Property for identifying whether the object is new or old,     * will insert(new) or update(old)     * If is new and id/bin is duplicate, org.hibernate.exception.ConstraintViolationException will be thrown.     * If is old and id/bin is duplicate, just updates. Hibernate save() will upsert and no complain.     */    @Transient    private boolean isNewObject;    @Override    public String getId() {        return this.bin;    }    @Override    public boolean isNew() {        return isNewObject;    }    @Override    public String getId() {        return this.bin;    }    @Override    public boolean isNew() {        return isNewObject;    }
查看完整描述

2 回答

?
縹緲止盈

TA貢獻2041條經驗 獲得超4個贊

如果您調用save()現有實體,Hibernate 不會再次保留它,而只會更新該實體。


查看完整回答
反對 回復 2021-07-14
?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

最后我中止了這個測試,并通過不檢查異常來繞過它。它仍然是一個錯誤。


查看完整回答
反對 回復 2021-07-14
  • 2 回答
  • 0 關注
  • 214 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號