我有两个名为Customer和他的Biiling Address的实体。这种关系是一对一的。每个客户都有一个账单地址。我想在客户被持久化时自动持久化计费地址。客户id是customer实体的主键,也是地址实体中的主键和外键。
//parent table
public class CustomerDTO implements Serializable {
@Id
@GeneratedValue
@Column(name = "customer_id")
private Integer id;
@OneToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL )
@PrimaryKeyJoinColumn(name="customer_id")
BillingAddressDTO billingAddressDTO;
//child table
public class BillingAddressDTO implements Serializable {
@Id
@Column(name="customer_id")
private Integer id;
这是我用来持久化实体的代码
customerDTO = new CustomerDTO();
customerDTO.setFirstName(firstName);
billingAddressDTO = new BillingAddressDTO();
billingAddressDTO.setBillingAddress(address1);
customerDTO.setBillingAddressDTO(billingAddressDTO);
//persisting customer entity
customerDAO.persist(customerDTO);
我得到以下异常
Caused by: org.hibernate.id.IdentifierGenerationException: ids for this
class must be manually assigned before calling save():
我想给地址表分配相同的客户id,所以我不想手动分配。谢谢你抽出时间。
您需要的是所谓的派生标识符。在这种方法中,CustomerDTO
(父实体)的主键与BillingAddressDTO
(从属实体)共享。
@Entity
public class CustomerDTO implements Serializable {
@Id
@GeneratedValue
@Column(name = "customer_id")
private Integer id;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn(name = "customer_id")
private BillingAddressDTO billingAddressDTO;
...
}
@Entity
public class BillingAddressDTO implements Serializable {
@Id
private Integer id; // @Column is NOT allowed since id is indicated by @MapsId
@MapsId
@OneToOne(mappedBy = "billingAddressDTO")
@JoinColumn(name = "customer_id")
private CustomerDTO customerDTO;
...
}
在上述场景中,父实体CustomerDTO
具有简单主键customer_id
,并且从属实体BillingAddressDTO
共享由关系属性customerDTO
映射的单个主键属性。
更新:基于阿里评论的替代解决方案,避免双向关系
@Entity
public class CustomerDTO implements Serializable {
@Id
private Integer id;
@MapsId
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "customer_id")
private BillingAddressDTO billingAddressDTO;
...
}
@Entity
public class BillingAddressDTO implements Serializable {
@Id
@GeneratedValue
@Column(name = "customer_id")
private Integer id;
...
}
在上述场景中,父实体BillingAddressDTO
具有简单主键customer_id
,并且从属实体CustomerDTO
共享由关系属性billingAddressDTO
映射的单个主键属性。
从底层数据库的角度来看,实体将如下所示:
customer_id firstname
----------- ---------
1 Ali Baba
customer_id billingaddress
----------- --------------
1 my_address
参考文献:
- JPA 2.0规范,第2.4.1章:与派生标识相对应的主键