我正在使用JPA Hibernate和@OneToOne
使用外键方法。添加& amp时出现问题更新我的数据。
我的问题是:
1)我只想将数据插入 Customer 表,但它也会将空值插入 CustomerInfo 表。
2)我只想更新客户表。但它也会将空值插入 CustomerInfo ,并将PK
更新回客户的FK
。
表格设计
班级:客户
Customer{
customerId(PK),
name,
customerInfoId(FK)
}
CustomerInfo{
customerInfoId(PK),
address1,
address2,
address3}
@OneToOne(fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
@JoinColumn(name = "customerInfoId", nullable = true, updatable = true, insertable = true)
private CustomerInfo customerInfo;
输入数据:
客户(名称= “GARY”),
CustomerInfo-No Input(空字符串)< - Spring MVC将其默认设置为空字符串。
来自DB的结果 :
Customer:
customerId("1"),
name("GARY"),
customerInfoId("1")<--this should be null
CustomerInfo:
customerInfoId("1")<--don't know why JPA hibernate insert into this table as there is no data input
客户(名称= 'GARY123'),
CustomerInfo-No Input(空字符串)&lt; - 默认情况下,Spring mvc将设置为空字符串。
Customer:
customerId("1")
name("GARY123")
customerInfoId("2") - this should be null
CustomerInfo:
customerInfoId("2) - don't know why JPA Hibernate insert into this table as there is no input data
Hibernate SQL for update Customer:
insert into CUSTOMERINFO(CUSTOMERINFOID, ADDRESS1, ADDRESS2, ADDRESS3) values (default, ?, ?, ?);
update CUSTOMER set name =?, customerInfoId = ? where CUSTOMERID = ?
以下是我打电话给创作&amp;更新客户:
@Override
public void create(CustomerObj obj) {
Customer entity = new Customer();
entity.setName(obj.getName());
CustomerInfo customerInfo = new CustomerInfo();
customerInfo.setAddress1(obj.getCustomerInfo().getAddress1());
customerInfo.setAddress2(obj.getCustomerInfo().getAddress2());
customerInfo.setAddress3(obj.getCustomerInfo().getAddress3());
entity.setCustomerInfo(customerInfo);
persistAndFlush(entity);
}
@Override
public void update(CustomerObj obj) {
Customer entity = findById(obj.getCustomerId)
entity.setName(obj.getName());
CustomerInfo customerInfo = new CustomerInfo();
customerInfo.setAddress1(obj.getCustomerInfo().getAddress1());
customerInfo.setAddress2(obj.getCustomerInfo().getAddress2());
customerInfo.setAddress3(obj.getCustomerInfo().getAddress3());
entity.setCustomerInfo(customerInfo);
}