java – JPA:@Embeddable对象如何获得对其所有者的引用?

我有一个User类,@Embedded一个类Profile.如何给Profile的实例给它的所有者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 ..
}

解决方法

假设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关系,或者简单地将“简档”类放入“用户”. @Embeddable的主要理由是代码重用,在这种情况下似乎不太可能.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...