JPA: Как объект @Embeddable получает ссылку на своего владельца?
У меня есть класс User, у которого @Embedded профиль класса. Как я могу предоставить экземплярам профиля ссылку на своего владельца класса 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 ..
}
Ответы
Ответ 1
Предполагая, что 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
См. официальную документацию, раздел 2.4.3.4., http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/, вы можете использовать @org.hibernate.annotations.Parent
, чтобы дать объекту Profile обратный указатель на свой собственный объект пользователя и реализовать получатель пользовательского объекта.
@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 ..
}