且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

外键必须与引用的主键具有相同的列数

更新时间:2023-02-02 23:42:16

  @MapsId(subDienstId)
@ManyToOne
private ProxyDienst subDienst;

@MapsId(parentDienstId)
@ManyToOne
私人ProxyDienst parentDienst;

您的情况 parentDienstId 是PK但也扮演着FK的角色。这被称为衍生身份。在JPA 2专书中有一篇关于它的好章节。


I know this topic is discussed a lot of times here, but I am still stuck on an exception: Foreign key must have same number of columns as the referenced primary key.

(I am using spring data and hibernate)

My ID class:

    @Embeddable
public class ProxyDienstRelationPK implements Serializable{

    private static final long serialVersionUID = 1L;

    @Column
    private String parentDienstId;
    @Column
    private String subDienstId;


    public ProxyDienstRelationPK(){}

    public ProxyDienstRelationPK(ProxyDienst parentDienst, ProxyDienst subDienst){
        this.parentDienstId = parentDienst.getId();
        this.subDienstId = subDienst.getId();
    }

   //Getter and Setter , HashCode and Equals

}

My Entity:

    @Entity
public class ProxyDienstRelation {

    @EmbeddedId
    private ProxyDienstRelationPK pdId;

    private ProxyDienst subDienst;

    private ProxyDienst parentDienst;


    private boolean modul;

    //Getter and Setter   
}

I get for this construction the following exception:

Caused by: org.hibernate.MappingException: Foreign key (FK_ad3h9gu4labg6ix34bei3poxt:proxy_dienst_relation [parent_dienst_id,sub_dienst_id])) must have same number of columns as the referenced primary key (proxy_dienst [id]) at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:110) at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:93) at org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1816) at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1739) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1424) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) ... 23 more

Hope someone can help. Thanks

@MapsId("subDienstId")
@ManyToOne
private ProxyDienst subDienst;

@MapsId("parentDienstId")
@ManyToOne
private ProxyDienst parentDienst;

In your case parentDienstId is part of PK but also plays role as a FK. This is called "Derived Identities". There is a good chapter about it in Pro JPA 2 book.