我在mysql中有一个customer表和一个Address表。结构如下:
customer:{customer_id, name, email, shipping_address_id, mailing_address_id}
address:{address_id, street_name, suburb, state, postcode}
shipping_address_id, mailing_address_id
是customer表中的外键,它引用地址表中的address_id
。
shipping_address_id, mailing_address_id
与@OneToOne
具有address_id
单向关系。
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "shipping_address_id")
private Address shippingAddress;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "billing_address_id")
private Address billingAddress;
我设法写了一个休息端点,我可以使用以下有效负载将数据插入到这些表中:
{
"name": "testName",
"email": "test@test.com",
"shippingAddress": {
"streetAddress": "Strert1",
"suburb": "TestSuburb",
"state": "TestState",
"postcode": "TestPostcode"
},
"mailingAddress": {
"streetAddress": "Strert1",
"suburb": "TestSuburb",
"state": "TestState",
"postcode": "TestPostcode"
}
}
唯一的问题是shipping_address和邮寄地址相同时,它会两次插入地址。有没有办法在地址中插入记录之前先检查?如果地址存在,是否可以将现有地址链接到客户?
很高兴为需要时提供映射代码。我没有在CrudRepository.save方法上定义任何规范
编辑:根据m.aibin的建议实施
控制器
@RequestMapping(value = "/customer", method = POST)
public ResponseEntity<String> addCustomer(@RequestBody Customer customer) {
try {
customerService.createCustomer(customer);
}
catch (Exception ex) {
return new ResponseEntity<>("Error creating the user: " + ex.toString(), INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>("User succesfully created! (id = " + customer.getCustomerId() + ")", OK);
}
服务
public void createCustomer(Customer customer) {
if(customer.getBillingAddress().equals(customer.getShippingAddress())){
customer.setShippingAddress(null);
Customer savedCustomer = customerRepository.save(customer);
customer.setShippingAddress(savedCustomer.getBillingAddress());
customerRepository.save(customer);
}
else {
customerRepository.save(customer);
}
}
它有效:)。只是想知道是否有一个基于规范的方法来实现这个我可以做类似的事情?
customerRepository.save(modifiedSave(customer))
答案 0 :(得分:0)
如果列没有限制为非null,则可以执行以下操作:
检查地址是否相同
如果是,则保存没有邮件地址对象的Customer对象(此方法可以返回Address对象)。然后将Address对象设置为customer作为Mailing id并更新DB中的Customer对象。
如果值不相同,只需进行一次保存。
希望你理解我的思维方式;)