JPA中的JoinTable用于3个不同的实体

时间:2015-06-25 19:48:35

标签: java hibernate jpa

我正在尝试使用来自3个不同实体的@JoinTable创建连接表。下面是我正在使用的代码示例。在创建连接表时,我遇到了错误。请帮忙解决。

我的设计中有3个实体。凭证,类别和承租人。 现在我正在尝试使用它们之间的@ManyToMany注释创建一个包含这3个表的pk的连接表。以下是我正在努力建立的关系。

enter image description here

@Entity
    @Table(name = "CREDENTIALS")

    public class CredentialsEntity {

        /** The credential id. */
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "ID")
        private int credentialId;   

        @ManyToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE})
        @JoinTable(name = "CATEGORY_HAS_CREDENTIALS",
                joinColumns = {
                @JoinColumn(table="CATEGORY", name = "CATEGORY_ID", referencedColumnName = "ID"),
                @JoinColumn(table ="TENANT", name = "TENANT_ID", referencedColumnName = "ID")},
                inverseJoinColumns = @JoinColumn(table="CREDENTIALS", name = "CREDENTIAL_ID", referencedColumnName = "ID"))
        private List<TenantEntity> tenantEntities;
    }

==========================

    @Entity
    @Table(name = "TENANT")

    public class TenantEntity {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "ID")
        private int tenantId;

         @ManyToMany(mappedBy = "tenantEntities", cascade = CascadeType.ALL)    
         private List<CredentialsEntity> credentialsEntities;
}

==========================

@Entity
@Table(name = "CATEGORY")
public class NodeCategory {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private int categoryId;

    @ManyToMany(cascade = CascadeType.ALL)  
    private List<CredentialsEntity> credentialsEntities;
}

引起:

  

org.hibernate.AnnotationException:无法找到预期的辅助   表:没有TENANT可用   com.aricent.aricloud.entity.CredentialsEntity at   org.hibernate.cfg.Ejb3Column.getJoin(Ejb3Column.java:363)at   org.hibernate.cfg.Ejb3Column.getTable(Ejb3Column.java:342)at   org.hibernate.cfg.Ejb3Column.checkPropertyConsistency(Ejb3Column.java:584)     在   org.hibernate.cfg.annotations.CollectionBinder.buildCollectionKey(CollectionBinder.java:1018)     在   org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1336)

修改

我可以像link

中提到的那样进行如下所示的连接表

这是正确的做法还是我做错了什么?

@ManyToMany(cascade={CascadeType.ALL})
@JoinTable(name = "CATEGORY_HAS_CREDENTIALS",
            joinColumns = {
            @JoinColumn(name = "CREDENTIAL_ID", referencedColumnName = "ID")},
            inverseJoinColumns = @JoinColumn(table = "CATEGORY", name = "CATEGORY_ID", referencedColumnName = "ID"))
            @MapKeyJoinColumn(name = "TENANT_ID", referencedColumnName ="ID")
            @ElementCollection
            private Map<TenantEntity, NodeCategory> tenantCategoryMap = new HashMap<TenantEntity, NodeCategory>();

0 个答案:

没有答案