在我的项目中,我使用EclipseLink作为 JPA 实现。我有两个实体,Product 和 ProductDetail:
-
他们有 one-to-one 关系。一个产品应该只有一个 ProductDetail。
-
ProductDetail 不能为 null。一个产品应始终具有 ProductDetail。
-
这种关系是单向的。我只会从 Product 访问 ProductDetail。
-
这两个实体应该具有共享主键,Product 的“id”应该等于 ProductDetail 的“prodId”。
所以我设计了如下的实体模型:
@Table(name="product")
public class Product{
@Id
@GeneratedValue(generator = "PRODUCT_ID")
@UuidGenerator(name = "PRODUCT_ID")
@Column(name = "id", unique=true, nullable=false, length=200)
private String id;
// Some other properties....
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
@PrimaryKeyJoinColumn
private ProductDetail productDetail;
}
@Table(name="product_detail")
public class ProductDetail{
@Id
@Column(name = "prod_id", unique=true, nullable=false, length=200)
private String prodId;
// Some other properties....
}
但懒惰的取物从来没有奏效。始终使用产品获取 ProductDetail。我检查了很多文件,但仍然无法弄明白。有没有人有这方面的经验?非常感谢!
注意:我正在使用 EclipseLink 但不使用 Hibernate。
1 回答
要在 toOne 关系上进行延迟加载,EclipseLink 必须在引用中注入代理。这个过程叫做“编织”。
默认情况下不启用此功能,因此您必须查看文档如何为运行时环境启用编织:
https://www.eclipse.org/eclipselink/documentation/2.7/solutions/testingjpa004.htm#CHDEECDB