Java Spring JPA@OneToOne双向空字段
我有两个类,一个是Customer,这个Customer有CustomerAccount类实例。像这样,Java Spring JPA@OneToOne双向空字段,java,spring,hibernate,spring-data-jpa,Java,Spring,Hibernate,Spring Data Jpa,我有两个类,一个是Customer,这个Customer有CustomerAccount类实例。像这样, @Entity @Table(name="tbl_customer") public class Customer extends BaseModel { private static final long serialVersionUID = 6330478175909499801L; @Id @GeneratedValue(strategy = Genera
@Entity
@Table(name="tbl_customer")
public class Customer extends BaseModel {
private static final long serialVersionUID = 6330478175909499801L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator="customer_s")
@SequenceGenerator(name="customer_s", sequenceName="customer_s", allocationSize=1)
@Column(name="id")
private Integer id;
@JoinColumn(name = "customer_account_id")
@OneToOne(mappedBy = "customer", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
private CustomerAccount customerAccount;
public CustomerAccount getCustomerAccount() {
return customerAccount;
}
public void setCustomerAccount(final CustomerAccount customerAccount) {
if (customerAccount == null) {
if (this.customerAccount !=null) {
this.customerAccount.Customer(null);
}
} else {
customerAccount.setCustomer(this);
}
this.customerAccount = customerAccount;
}
//..
}
@Entity
@Table(name="tbl_customer_account")
public class CustomerAccount extends BaseModel {
private static final long serialVersionUID = 3995542305560456290L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "customer_account_s")
@SequenceGenerator(name = "customer_account_s", sequenceName = "customer_account_s", allocationSize = 1)
@Column(name="id")
private Integer id;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Customer customer;
//..
}
这是我的CustomerServiceImpl
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerDao customerDao;
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
private void saveOrUpdate(final CustomerResult result) throws Exception {
CustomerMapper.getInstance().dtoToDomain(result.getDtoEntity(), result.getDomainEntity());
setCustomerData(result);
customerDao.save(result.getDomainEntity());
result.updateDtoIdAndVersion();
}
private void setCustomerData(final CustomerResult result) throws Exception{
final CustomerAccount customerAccount = new CustomerAccount();
customerAccount.setCustomer(result.getDomainEntity());
result.getDomainEntity().setCustomerAccount(customerAccount);
}
}
我的问题是当我将Customer、Customer和CustomerAccount持久化到数据库时。但在客户实体中,“customerAccount”字段为空。我还引用了本文您希望CustomerAccount ID通过使用MapsId与CustomerId相同。所以不要告诉JPA它应该使用序列生成器生成ID:它不应该。从帐户id中删除
@GeneratedValue
和@SequenceGenerator
。就像。。。在你链接到的文章中。为了确保在保存后填充ID,您需要刷新(),而不仅仅是保存()。为什么有@MapsId?我想你不会想要的。所以删除它。如果我删除'@MapsId',我如何映射'Customer'和'CustomerAccount'实体@Simon删除客户端的@JoinColumn(name=“supplier\u account\u id”)并删除@MapsId,然后一切都应该正常。不幸的是,结果是相同的@SimonMartinelli