【问题标题】:Is there a way to map child entity to parent entity using parent entity field (not parent object)?有没有办法使用父实体字段(不是父对象)将子实体映射到父实体?
【发布时间】:2019-05-06 19:11:23
【问题描述】:

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

@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,可以吗?

【问题讨论】:

  • 你为什么需要这样做?
  • @Alan Hay 因为 Customer 是一个“大”对象,我不想将它存储在内存中。我知道休眠中有一个惰性获取类型选项。但在这种情况下,我不需要机会从 Customer 对象获取信息,我只需要它的 id。

标签: java hibernate jpa


【解决方案1】:

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

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

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

【讨论】:

  • 不幸的是,这种方式休眠不会创建外键。我认为最好的解决方案是保持原样,并依赖延迟初始化选项。
  • 没有别的办法。
猜你喜欢
  • 2016-10-22
  • 2012-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
  • 1970-01-01
  • 2020-11-04
相关资源
最近更新 更多