JPA:@Embeddable对象如何获取对其所有者的引用?

我有一个具有@Embedded类配置文件的User类。 如何为Profile的实例提供对其所有者User类的引用?

@Entity class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Embedded Profile profile; // .. other properties .. } @Embeddable class Profile implements Serializable { User user; // how to make this work? setURL(String url) { if (user.active() ) { // for this kind of usage // do something } } // .. other properties .. } 

假设JPA而不是严格的Hibernate,您可以通过将@Embedded应用于getter / setter对而不是私有成员本身来实现。

 @Entity class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Access(AccessType.PROPERTY) @Embedded private Profile profile; public Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; this.profile.setUser(this); } // ... } 

但是,在这种情况下,我会质疑嵌入式实体是否是您想要的,而不是@OneToOne关系,或者只是将Profile类“展平”为User。 @Embeddable的主要原理是代码重用,在这种情况下似乎不太可能。

请参阅官方文档,第2.4.3.4节。 , http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/ ,您可以使用@org.hibernate.annotations.Parent为Profile对象提供一个指向其拥有的User对象的后向指针,实现用户对象的getter。

 @Embeddable class Profile implements Serializable { @org.hibernate.annotations.Parent User user; // how to make this work? setURL(String url) { if (user.active() ) { // for this kind of usage // do something } } User getUser(){ return this.user; } // .. other properties .. }