Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Serializable {

   User user; // how to make this work?

   setURL(String url) {
      if (user.active() ) { // for this kind of usage
         // do something
      }
   }

   // .. other properties ..
}
like image 944
Kdeveloper Avatar asked Feb 20 '11 23:02

Kdeveloper


1 Answers

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 ..
}
like image 118
Ken Chan Avatar answered Nov 10 '22 14:11

Ken Chan