Hibernate中与复合键的多对多关系

时间:2013-02-08 15:32:09

标签: java hibernate mapping composite-key

有没有办法使用@JoinTable注释,用两个字段连接每个表?以下是示例表:

+----------------+  +----------------------------------+  +----------------+      
| example_table  |  | example_table_to_some_type_table |  | some_type_table|
+----------------+  +----------------------------------+  +----------------+   
|example_table_id|  |example_table_id                  |  |some_type_id    |
|another_id      |  |some_type_id                      |  |another_id      |
|...             |  |another_id                        |  |...             |
|other columns   |  +----------------------------------+  |other columns   |
|...             |                                        |...             | 
+----------------+                                        +----------------+

对于多对一的案例,它看起来像这样:

@ManyToOne
@JoinColumns({ @JoinColumn(name = "some_type_id", 
    referencedColumnName = "some_type_id", 
    insertable = false, updatable = false),
               @JoinColumn(name = "another_id", 
    referencedColumnName = "another_id", 
    insertable = false, updatable = false) })
private SomeType someType;

但多对多关系怎么样?我尝试了以下内容,但没有奏效:

@ManyToMany(targetEntity = SomeType.class)
@JoinTable(name = "example_table_to_some_type_table", 
    joinColumns = { @JoinColumn(name = "example_table_id"),  
                    @JoinColumn(name = "another_id") }, 
    inverseJoinColumns = { 
                    @JoinColumn(name = "some_type_id"),  
                    @JoinColumn(name = "another_id") })
private Set<SomeType> someTypeSet;

我收到以下错误:

Repeated column in mapping for collection: com.package.name.Example.someTypeSet column: another_id

我应该看一下这个映射的哪个部分不正确?提前谢谢。

1 个答案:

答案 0 :(得分:2)

您的联接表需要4列。 2引用example_table和其他2的PK列以引用some_type_table的PK列。

所以看起来应该是

+----------------+  +----------------------------------+  +----------------+      
| example_table  |  | example_table_to_some_type_table |  | some_type_table|
+----------------+  +----------------------------------+  +----------------+   
|example_table_id|  |example_table_id                  |  |some_type_id    |
|another_id      |  |example_table_another_id          |  |another_id      |
|...             |  |some_type_id                      |  |...             |
|                |  |some_type_table_another_id        |  |                |
|other columns   |  +----------------------------------+  |other columns   |
|...             |                                        |...             | 
+----------------+                                        +----------------+