首页 > 解决方案 > 有没有办法使用父实体字段(不是父对象)将子实体映射到父实体?

问题描述

我正在尝试对一对多的单向关联进行建模。我有两个实体,第一个(父)是:

@Entity
@Table(name = "customer")
public class Customer{
@Id
@Column(name = "ID")
private Long id;    

第二个实体与客户具有多对一关系:

@Entity
@Table(name = "address")
public class Address{
@Id    
@Column(name = "ID")
private Long id;        
@ManyToOne(optional = false)
@JoinColumn(name = "CUSTOMER_ID", referencedColumnName = "ID")
private Customer customer;

我需要用 customer.id 替换 Address 类中的属性 Customer,这可能吗?

标签: javahibernatejpa

解决方案


您可以使用 Adress 实体中的 customerId 字段并使用 JPQL 手动加入它,但不建议这样做,也不会创建外键。

@Entity
@Table(name = "address")
public class Address{
@Id    
@Column(name = "ID")
private Long id;        

@Column(name = "CUSTOMER_ID")
private Long customerId;

推荐阅读