有没有一种方法可以使用@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


我应该看什么,该映射的哪一部分不正确?提前致谢。

最佳答案

您的联接表需要4列。 2引用example_table的PK列,另2引用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   |
|...             |                                        |...             |
+----------------+                                        +----------------+

10-06 08:44