JPA:@Embeddable对象如何获得对其所有者的引用? [英] JPA: How can an @Embeddable object get a reference to its owner?
问题描述
我有一个拥有@Embedded类Profile的User类。如何将配置文件的实例提交给其所有者User类?
@Entity
class User implements可串行化{
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@嵌入式配置文件配置文件;
// ..其他属性..
}
@Embeddable
class Profile实现Serializable {
用户用户; //如何使这项工作?
setURL(String url){
if(user.active()){//这种用法
//做某事
}
}
// ..其他属性..
}
@Entity
class User实现Serializable {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
私人整数ID;
@Access(AccessType.PROPERTY)
@Embedded
私人个人资料个人资料;
public Profile getProfile(){
return profile;
}
public void setProfile(Profile profile){
this.profile = profile;
this.profile.setUser(this);
}
// ...
}
<但是,在这种情况下,我会质疑一个嵌入式实体是否是您想要的,而不是@OneToOne关系,或者简单地将Profile类扁平化为User。 @Embeddable的主要基本原理是代码重用,在这种情况下似乎不太可能。
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?
@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 ..
}
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.
@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.
这篇关于JPA:@Embeddable对象如何获得对其所有者的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!