Java – JPA: @ embeddable object how to get a reference to its owner?
•
Java
I have a user class, @ embedded a profile class How to give an instance of a profile a user class reference to its owner?
@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 ..
}
Solution
Assuming JPA instead of strict hibernate, you can implement @ embedded by applying @ embedded to getter / setter pairs instead of private members themselves
@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, in this case, I will question whether the embedded entity is what you want, not the @ onetoone relationship, or simply put the "profile" class into the "user"@ The main reason for embeddable is code reuse, which seems unlikely in this case
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
