JPA: How can an @Embeddable object get a reference to its owner?

前端 未结 2 1445
醉梦人生
醉梦人生 2021-02-08 02:35

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 imp         


        
相关标签:
2条回答
  • 2021-02-08 02:54

    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.

    0 讨论(0)
  • 2021-02-08 03:11

    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 ..
    }
    
    0 讨论(0)
提交回复
热议问题