Hibernate @ManyToMany使用复合键进行映射

时间:2008-10-13 13:54:17

标签: java hibernate java-ee

我正在尝试在两个表之间映射ManyToMany关系,两个表都有复合主键

LSFOCTB which primary key is composed of : LSFOC_CODSOC,LSFOC_CODLSC,LSFOC_CODFOC

LSFORTB which primary key is composed of : LSFOR_CODSOC,LSFOR_CODLSC,LSFOC_CODFOR

The table in charge of the ManyToMany relationship is :

LSFCFTB, with : LSFCF_CODSOC,LSFCF_CODLSC,LSFCF_CODFOC,LSFCF_CODFOR

所以,在hibernate模型映射LSFOCTB中,我试过:

@ManyToMany(targetEntity = package.LSFOCTB.class, cascade = { CascadeType.PERSIST,
            CascadeType.MERGE })
    @JoinTable(name = "LSFCFTB", joinColumns = {
            @JoinColumn(name = "LSFCF_CODLSC", referencedColumnName = "LSFOC_CODLSC"),
            @JoinColumn(name = "LSFCF_CODFOC", referencedColumnName = "LSFOC_CODFOC"),
            @JoinColumn(name = "LSFCF_CODSOC", referencedColumnName = "LSFOC_CODSOC") }, 
    inverseJoinColumns = { @JoinColumn(name = "LSFCF_CODLSC", referencedColumnName = "LSFOR_CODLSC"),
            @JoinColumn(name = "LSFCF_CODFOR", referencedColumnName = "LSFOR_CODFOR"),
            @JoinColumn(name = "LSFCF_CODSOC", referencedColumnName = "LSFOR_CODSOC") })
在吸气器之前

。 但它不会起作用...... 尝试访问远程集合时的错误是:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [beans-dao.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Repeated column in mapping for collection: package.LSFOCTB.distantCollection column: LSFCF_CODLSC

是否已经设法让一个Hibernate映射为ManyToMany关系工作? 如果是这样,我的映射有什么问题? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

问题似乎是您正在创建一个包含6列的连接表,并且列的名称重复。您实际上创建了2个名为 LSFCF_CODLSC 的列和2个名为 LSFCF_CODFOR 的列和2个名为 LSFCF_CODSOC 的列。

我建议你试试这个:

@JoinTable(name = "LSFCFTB", joinColumns = {
                    @JoinColumn(name = "LSFOC_LSFCF_CODLSC", referencedColumnName = "LSFOC_CODLSC"),
                    @JoinColumn(name = "LSFOC_LSFCF_CODFOC", referencedColumnName = "LSFOC_CODFOC"),
                    @JoinColumn(name = "LSFOC_LSFCF_CODSOC", referencedColumnName = "LSFOC_CODSOC") }, 
        inverseJoinColumns = { @JoinColumn(name = "LSFOR_LSFCF_CODLSC", referencedColumnName = "LSFOR_CODLSC"),
                    @JoinColumn(name = "LSFOR_LSFCF_CODFOR", referencedColumnName = "LSFOR_CODFOR"),
                    @JoinColumn(name = "LSFOR_LSFCF_CODSOC", referencedColumnName = "LSFOR_CODSOC") })

或类似的东西(根据您的命名约定)为每列提供唯一的名称。