JPA: How can an @Embeddable object get a reference to its owner?
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 Seriali开发者_如何学编程zable {
User user; // how to make this work?
setURL(String url) {
if (user.active() ) { // for this kind of usage
// do something
}
}
// .. other properties ..
}
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 .
@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 ..
}
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.
精彩评论