0

我有这两张表:

CREATE TABLE IF NOT EXISTS `functions` (
`idFunction` int(11) NOT NULL,
`idLanguage` int(11) NOT NULL,
`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`idCategory` int(11) DEFAULT '1',
PRIMARY KEY (`idFunction`,`idLanguage`),
KEY `idCategory` (`idCategory`),
KEY `idLanguage` (`idLanguage`),
CONSTRAINT `FK_functions_categories` FOREIGN KEY (`idCategory`) REFERENCES            
`category_package` (`idCategory`) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT `FK_functions_languages` FOREIGN KEY (`idLanguage`) REFERENCES `languages`  (`idLanguage`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `subfunctions` (
`idParent` int(11) NOT NULL,
`idChild` int(11) NOT NULL,
PRIMARY KEY (`idParent`,`idChild`),
KEY `idChild` (`idChild`),
CONSTRAINT `FK_subfunctions_functions` FOREIGN KEY (`idParent`) REFERENCES `functions` (`idFunction`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_subfunctions_functions_2` FOREIGN KEY (`idChild`) REFERENCES `functions` (`idFunction`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

当我尝试通过 Hibernate 的逆向工程映射这些表时,会发生映射,但是当我尝试执行涉及这两个表的查询时,Hibernate 会抛出这个异常:

Foreign key (FKFD0F515B161D5928:subfunctions [idParent])) must have same number of columns as the referenced primary key (functions [idFunction,idLanguage])

我知道真正的交易是将 idLanguage 作为 PK 也放在子函数表中,但我使用的是旧版数据库,我无法修改它。

有没有办法映射这个?

4

1 回答 1

0

您没有提供很多有关映射的详细信息,因此在这里为您提供帮助并不容易。通常,由于两个表的主键都是复合键,因此可以将其映射到可嵌入类中,如http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e2177中所示

上述类的示例映射可能类似于:

@Entity
@Table(name = "functions")
public class Functions {

    @Id
    private FunctionPK functionPK;

    @Column(name="name", nullable=false)
    private String name;

    @Column(name="idCategory", nullable=false)
    @ManyToOne(cascade=CascadeType.SAVE_UPDATE)
    @JoinColumn(name = "idCategory")
    private CategoryPackage idCategory;

...
}

@Embeddable 
  private class FunctionPK implements Serializable
  {

    @Column(name="idFunctions")
    private int idFunctions;

    @Column(name="idLanguage")
    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "idLanguage")
    private Language idLanguage;

    //Some getters and setters 
    ...
  }

@Entity
@Table(name = "subfunctions")
public class SubFunctions {

    @Id
    private SubFunctionPK subFunctionPK;

...
}

@Embeddable 
  private class SubFunctionPK implements Serializable
  {

    @Column(name="idParent")
    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "idFunction")
    private Functions idParent;

    @Column(name="idChild")
    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "idFunction")
    private Functions idChild;

    //Some getters and setters 
    ...
  }
于 2012-09-19T13:36:53.273 回答