- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在 Java Spring Boot 应用程序中使用 H2 作为测试数据库,但是当我想在尝试插入重复的 ID/PK 时捕获“重复键”异常时,H2 不会抛出任何内容。
有了 Postman,一切都很好,只是我无法通过测试。
真正的数据库是PostgreSQL,当我与Postman集成测试时,它确实抛出异常。但在单元测试时我认为没有必要加载真实的DB所以我选择了H2。
H2 配置:
spring.datasource.url=jdbc:h2:mem:tesdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;mode=MySQL
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1
spring.jpa.datasource.show-sql=true
spring.h2.console.enabled=true # if you need console
Bean 定义:
@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;
}
Controller insert
方法:
@RequestMapping(value="/insert", method=RequestMethod.POST)
public ResponseEntity<Object> insertBIN(@Valid @RequestBody BinInfo bin_info, HttpServletResponse response) throws JsonProcessingException {
Map<String, Object> errors = new HashMap<String, Object>();
try {
OffsetDateTime now = OffsetDateTime.now();
bin_info.setCreatedAt(now);
bin_info.setUpdatedAt(now);
bin_info.setNewObject(true); //if set to true, bin duplicate -> exception and return 200; then we avoid "select to check duplicate first"
BinInfo saved = repository.save(bin_info);
// if is new, created(201); if not, updated(status OK, 200)
return ResponseEntity.status(HttpStatus.CREATED)
.contentType(MediaType.APPLICATION_JSON_UTF8).body(saved);
} catch (DataIntegrityViolationException e0) {
log.warn("Update BIN due to duplicate", e0); // exception details in log
//if duplicate, change newObject to false and save again. And return.
bin_info.setNewObject(false);
BinInfo saved = repository.save(bin_info);
return ResponseEntity.ok() // <<<<<< here I define "save duplicate=update=200, OK"
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(saved);
} catch (Exception e) {
log.error("Cannot save BinInfo. ", e); // exception details in log
errors.put("error", "Cannot save BIN"); // don't expose to user
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(Utilities.jsonBuilder(errors));
}
测试:
@Test
public void testBinInfoControllerInsertBIN() throws Exception {
when(this.repository.save(any(BinInfo.class))).thenReturn(mockBinInfo);
String content_double_quotes = "{\"bin\":\"123456\", "
+ "\"json_full\":\"" + this.json_full + "\", "
+ "\"brand\":\"" + this.brand + "\", "
+ "\"type\":\"" + this.type + "\", "
+ "\"country\":\"" + this.country + "\", "
+ "\"issuer\":\"" + this.issuer + "\", "
+ "\"newObject\":true, "
+ "\"new\":true, "
+ "\"createdAt\":\"18/08/2018 02:00:00 +0200\", "
+ "\"updatedAt\":\"18/08/2018 02:00:00 +0200\"}";
log.info("JSON input: " + content_double_quotes);
//save the entity for the first time(newObject==true, new=true) and should return 201
this.mockMvc.perform(post("/insert")
.content(content_double_quotes) //json cannot have single quote; must be double
.accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
)
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isCreated())
.andDo(print())
.andExpect(jsonPath("$.bin", is(this.bin)))
.andExpect(jsonPath("$.json_full", is(this.json_full)))
.andExpect(jsonPath("$.brand", is(this.brand)))
.andExpect(jsonPath("$.type", is(this.type)))
.andExpect(jsonPath("$.country", is(this.country)))
.andExpect(jsonPath("$.issuer", is(this.issuer)))
.andExpect(jsonPath("$.createdAt", is("18/08/2018 02:00:00 +0200")))
.andExpect(jsonPath("$.updatedAt", is("18/08/2018 02:00:00 +0200")));
//save the same entity, new == true, and should return 200
this.mockMvc.perform(post("/insert")
.content(content_double_quotes) //json cannot have single quote; must be double
.accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk()); //<<<<< here I always get 201, not 200. With Postman I get 200 instead.
}
请注意, mockBinInfo
的 isNewObject
始终设置为 true
,这意味着在第二次插入中找到重复的 PK 时它应该抛出异常,但它没有发生。这是 Persistable<ID>
接口(interface)所需要的,它会告诉 DB 当 ID 重复或不重复时是否保留。
isNew()
返回 true
,当 ID 重复时会抛出异常请参阅 here 了解更多信息(搜索“Persistable”)。
编辑:
我还注意到H2似乎不支持Spring Persistable<ID>
并且总是在保存的实体中返回new=false
。
日志详细信息:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /insert
Parameters = {}
Headers = {Content-Type=[application/json;charset=UTF-8], Accept=[application/json;charset=UTF-8]}
Body = {"bin":"123456", "json_full":"{'brand':'visa', 'type':'credit', 'country':'USA', 'issuer':'BigBank'}", "brand":"visa", "type":"credit", "country":"USA", "issuer":"BigBank", "newObject":"true", "new":"true", "createdAt":"18/08/2018 02:00:00 +0200", "updatedAt":"18/08/2018 02:00:00 +0200"}
Session Attrs = {}
Handler:
Type = com.xxxxx.binlookup.controller.BinInfoController
Method = public org.springframework.http.ResponseEntity<java.lang.Object> com.xxxxx.binlookup.controller.BinInfoController.insertBIN(com.xxxxx.binlookup.model.BinInfo,javax.servlet.http.HttpServletResponse) throws com.fasterxml.jackson.core.JsonProcessingException
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 201
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"id":"123456","newObject":false,"new":false,"bin":"123456","json_full":"{'brand':'visa', 'type':'credit', 'country':'USA', 'issuer':'BigBank'}","brand":"visa","type":"credit","country":"USA","issuer":"BigBank","createdAt":"18/08/2018 02:00:00 +0200","updatedAt":"18/08/2018 02:00:00 +0200"}
Forwarded URL = null
Redirected URL = null
Cookies = []
最佳答案
如果您对现有实体调用 save()
,Hibernate 不会再次保留它,而只会更新该实体。
关于java - H2 - 当 Persistable<ID> isNewObject 设置为 true 时,重复键在 Spring 启动测试中不会引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51818627/
这个问题在这里已经有了答案: Why in Python does "0, 0 == (0, 0)" equal "(0, False)"? (7 个回答) 去年关闭。 代码片段 1: a = Tru
Integer i = 127; Integer j = 127; System.out.println(i == j); System.out.println(i.equals(j)); Integ
我试图用 Python 进行类似下面的代码的比较,但对产生的输出感到困惑。 谁能解释为什么输出是这样的? >>> True, True == True, True (True, True, True)
我们的下拉值是动态的 010100。 你能帮我将这些值转换为 true、false 吗? Offer的值是10100,Reject的值是10111。所以这些需要转换成 10100 = true,fal
我正在测试,如果用户在页面顶部显示一种货币“EUR”和另一种货币“GBP”,那么我期望包含文本“EUR”和页面下方还存在另一个包含文本“GBP”的链接。它包含在一个名为 "nav-tabs au-ta
如何检查数组的所有元素是真值还是假值。 因为以下内容似乎没有做到这一点:_.all([true, true, true], true); 它返回:false? 最佳答案 您应该重新阅读_.every(
C#:我有一个如下所示的字符串变量: string a = "(true and true) or (true or false)"; 这可以是任何东西,它可以变得更复杂,比如: string b
ruby : true == true == true syntax error, unexpected tEQ 对比JavaScript: true == true == true // => tr
这个问题已经有答案了: Equality of truthy and falsy values (JavaScript) (3 个回答) Which equals operator (== vs ==
为什么 R 中的 TRUE == "TRUE" 是 TRUE? R 中是否有与 === 等效的内容? 更新: 这些都返回FALSE: TRUE == "True" TRUE == "true" TRU
简单的查询,可能不可能,但我知道那里有一些聪明的人:) 给定一个 bool 参数,我希望定义我的 where 子句来限制特定列的输出 - 或不执行任何操作。 因此,给定参数@bit = 1,结果将是:
编写 Excel 公式时,将值设置为 true、“true”还是 true() 是否有区别? 换句话来说,以下哪一个是最好的?还是要看具体情况? if (A1 = 1, true, false) if
如果我们评估这个:TRUE AND TRUE,为什么会这样? 'yes' : 'no' 等于 TRUE 但不等于 yes 何时评估:(TRUE AND TRUE) ? 'yes' : 'no' 等于
这个问题在这里已经有了答案: Behaviour of and operator in javascript [duplicate] (1 个回答) 关闭 7 年前。 如题所说,我不太明白为什么(t
我有一个包含 FromDate 、 ToDate 、 VendorName 和 GoodsName 的表单,一旦一切为真,我需要显示结果 示例: FromDate="11/20/2019"、ToDat
我最近参加了 Java 的入门测试,这个问题让我很困惑。完整的问题是: boolean b1 = true; boolean b2 = false; if (b2 != b1 != b2) S
我有一个模型,我有: ipv4_address = models.IPAddressField(verbose_name=_('ipv4 address'), blank=True, null=Tru
False in [True,True] False in pd.Series([True,True]) 第一行代码返回False第二行代码返回 True! 我想我一定是做错了什么或者遗漏了什么。当我
我可以在 Coq 中证明以下内容吗? Lemma bool_uip (H1 : true = true): H1 = eq_refl true. 即true = true 的所有证明都相同吗? 例如
如果我的理解是正确的,他们做的事情完全一样。为什么有人会使用“for”变体?仅仅是味道吗? 编辑:我想我也在考虑 for (;;)。 最佳答案 for (;;) 通常用于防止编译器警告: while(
我是一名优秀的程序员,十分优秀!