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

前端 未结 2 1451
醉梦人生
醉梦人生 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.

提交回复
热议问题