java JPA:@Embeddable 对象如何获得对其所有者的引用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5060891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPA: How can an @Embeddable object get a reference to its owner?
提问by Kdeveloper
I have a User class that has @Embedded a class Profile. How can I give the instances of Profile a reference to their owner the User class?
我有一个 @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 ..
}
采纳答案by Jeff Caulfield
Assuming JPA rather than strictly Hibernate, you might do this by applying @Embedded
to a getter/setter pair rather than to the private member itself.
假设 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);
}
// ...
}
However, I would question whether an embedded entity is what you want at all in this case, as opposed to a @OneToOne relationship or simply "flattening" the Profile class into User. The main rationale for @Embeddable is code reuse, which seems unlikely in this scenario.
但是,我会质疑在这种情况下,嵌入的实体是否是您想要的,而不是 @OneToOne 关系或简单地将 Profile 类“展平”为 User。@Embeddable 的主要理由是代码重用,这在这种情况下似乎不太可能。
回答by Ken Chan
Refer to the official documentation ,section 2.4.3.4. , http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/, you can use @org.hibernate.annotations.Parent
to give the Profile object a back-pointer to its owning User object and implement the getter of the user object .
参考官方文档,第 2.4.3.4 节。, http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/,您可以使用@org.hibernate.annotations.Parent
给 Profile 对象一个指向其拥有的 User 对象的反向指针并实现 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 ..
}