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

Kde*_*per 10 java hibernate jpa

我有一个具有@Embedded类配置文件的User类.如何为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 ..
}
Run Code Online (Sandbox Code Playgroud)

Ken*_*han 11

请参阅官方文档,第2.4.3.4节.,http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/,您可以使用@org.hibernate.annotations.Parent它为Profile对象提供一个指向其拥有的User对象的后向指针,并实现用户对象的getter.

@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 ..
}
Run Code Online (Sandbox Code Playgroud)


小智 7

假设JPA而不是严格的Hibernate,您可以通过应用于@Embeddedgetter/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);
   }

   // ...
}
Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,我会质疑嵌入式实体是否是您想要的,而不是@OneToOne关系或简单地将Profile类"展平"为User.@Embeddable的主要原理是代码重用,在这种情况下似乎不太可能.

  • 我实际上赞成合成而不是继承.由于用户不仅仅是一件事,它实际上是由安全性,配置文件和设置等不同内容组成的. (3认同)
  • 我使用@Embedded的原因不是代码重用,而是为了获得更集中的小类而不是一个大的笨重的所有类. (2认同)