我在 Java Spring Boot 應(yīng)用程序中使用 H2 作為測試數(shù)據(jù)庫,但是當(dāng)我想在嘗試插入重復(fù)的 ID/PK 時捕獲“重復(fù)鍵”異常時,H2 不會拋出任何內(nèi)容。有了郵遞員,一切都很好,我就是無法通過測試。真正的數(shù)據(jù)庫是 PostgreSQL,當(dāng)我與 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; }
添加回答
舉報
0/150
提交
取消