没有主键ID的实体

时间:2015-08-25 15:52:28

标签: java spring jpa

您好我想创建一个没有ID的实体。

@Entity
@Table(name="USER_PROD_LIC_TYPE_ALL")
public class UserProdLicTypeAll {
   @EmbeddedId
   private UserProdLicTypeAllPK id;

   @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="USER_ID")
    private User user;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="LICENSE_TYPE_ID") 
    private LicenseType licType;
    ....
  }

因为它没有主键我创建了Embeddable类,如下所示:

 @Embeddable
 public class UserProdLicTypeAllPK {

  @ManyToOne(fetch=FetchType.LAZY)
  @JoinColumn(name="USER_ID")
  private User user;

  @ManyToOne(fetch=FetchType.LAZY)
  @JoinColumn(name="LICENSE_TYPE_ID")
  private LicenseType licType;
  ...
 }

这两个字段的组合返回唯一值。 但它不起作用。我得到了

org.springframework.beans.factory.UnsatisfiedDependencyException: exception

我是否需要在UserProdLicTypeAll和UserProdLicTypeAllPK的User和LicenseType实体中引用?我也试过了,但它仍然不起作用。

1 个答案:

答案 0 :(得分:0)

这是我的私人地狱。我不确定解决问题的最佳方法是什么。

我最好的解决方案是:

@Entity
@Table(name = TableName.AREA_USER)
@IdClass(UserAreaPK.class)
public class UserArea implements Serializable {
    private static final long   serialVersionUID    = 1L;

    @Id
    @Column(name = UserAreaPK.C_AREA_ID)
    private Long areaId;

    @Id
    @Column(name = UserAreaPK.C_USER_ID)
    private String userId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = UserAreaPK.C_AREA_ID, insertable = false, updatable = false)
    private Area area;

/**
 * Primary key for the relationship  User-Area
 */
public class UserAreaPK implements Serializable {

    protected static final String   C_AREA_ID           = "area_id";
    protected static final String   C_USER_ID           = "user_id";
    private static final long       serialVersionUID    = 1L;

    @Id
    @Column(name = C_AREA_ID)
    private Long                    areaId;

    @Id
    @Column(name = C_USER_ID)
    private String                  userId;