我在 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; }
添加回答
举报
0/150
提交
取消