简体   繁体   English

Hibernate复合键映射问题

[英]Hibernate composite key mapping issue

I'm trying to map entities of the same class (MyData) to each other through a mapping table. 我正在尝试通过映射表将相同类(MyData)的实体相互映射。 MyData has a composite primary key (id1 and id2). MyData具有复合主键(id1和id2)。 When I create the class (see below), it seems like Hibernate is reversing the order of the FK mappings (ie a_id1 is pointing to b_id2, etc...). 当我创建类时(见下文),似乎Hibernate正在反转FK映射的顺序(即a_id1指向b_id2,等等。。。)。 This does not seem right. 这似乎不正确。 Does the inverseJoinColumns have to be the opposite order of joinColums? inverseJoinColumns是否必须与joinColums的顺序相反? I couldn't find many examples online with composite keys... 我在网上找不到很多带有复合键的示例...

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;

Your mapping is wrong. 您的映射错误。 You need to add "referencedColumnName" to all of your JoinColumn annotations, eg 您需要在所有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")
})
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM