Hibernate复合键映射问题

时间:2009-07-10 18:57:45

标签: java hibernate

我正在尝试通过映射表将相同类(MyData)的实体映射到彼此。 MyData有一个复合主键(id1和id2)。当我创建类(见下文)时,似乎Hibernate正在颠倒FK映射的顺序(即a_id1指向b_id2等等)。这似乎不对。 inverseJoinColumns必须与joinColums的顺序相反吗?我在网上找不到很多复合键的例子......

public class MyData {
  // has composite key (id1, id2) 

  // ... //

  @ManyToMany
  @Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
  @JoinTable(name = "MyData_foo", 
    joinColumns = {
      @JoinColumn(name = "a_id1"), 
      @JoinColumn(name = "a_id2") 
    }, 
    inverseJoinColumns = {
      @JoinColumn(name = "b_id1"),
      @JoinColumn(name = "b_id2") })
  )
  private Set<MyData> mySet = new HashSet<MyData>();

  // ... //
}


CREATE TABLE `MyData_foo` (
  `b_id2` bigint(20) NOT NULL default '0',
  `b_id1` bigint(20) NOT NULL default '0',
  `a_id2` bigint(20) NOT NULL default '0',
  `a_id1` bigint(20) NOT NULL default '0',
  PRIMARY KEY  (`a_id1`,`a_id2`,`b_id1`,`b_id2`),
  KEY `FKCD44188BB2B7A1BE` (`b_id1`,`b_id2`),
  KEY `FKCD44188B7997E326` (`a_id1`,`a_id2`),
  CONSTRAINT `FKCD44188B7997E326` FOREIGN KEY (`a_id1`, `a_id2`) REFERENCES `MyData`  (`b_id2`, `b_id1`),
  CONSTRAINT `FKCD44188BB2B7A1BE` FOREIGN KEY (`b_id1`, `b_id2`) REFERENCES `MyData`  (`a_id2`, `a_id1`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

1 个答案:

答案 0 :(得分:3)

您的映射是错误的。您需要在所有JoinColumn注释中添加“referencedColumnName”,例如

@JoinTable(name = "MyData_foo",
 joinColumns = {
  @JoinColumn(name = "a_id1", referencedColumnName = "id1"), 
  @JoinColumn(name = "a_id2", referencedColumnName = "id2") 
}, 
inverseJoinColumns = {
  @JoinColumn(name = "b_id1", referencedColumnName = "id1"),
  @JoinColumn(name = "b_id2", referencedColumnName = "id2")
})
)