Hibernate没有发现默认值具有多个到同一实体的多个映射

时间:2013-01-28 17:10:36

标签: java hibernate orm

用户有以下内容:

@ManyToMany(mappedBy = "votedDownBy")
private Set<Foo> votedDown =new HashSet<Foo>();

@ManyToMany(mappedBy = "favouritedBy")
private Set<Foo> favourites = new HashSet<Foo>();

相应的Foo有这些:

@ManyToMany
private Set<User> votedDownBy = new HashSet<User>();

@ManyToMany
private Set<User> favouritedBy = new HashSet<User>();

部署时我没有为votedDownBy_id提供默认值...而且我不知道为什么?

2 个答案:

答案 0 :(得分:0)

@ManyToMany映射使用连接表完成。在您的情况下,必须有一个Foo_User表具有这些映射。即Foo_idUser_id列。 (将Foo_idUser_id替换为相应的主键。同时将Foo_User替换为Table1_Table2,其中Table1Foo和{{ 1}} Table2

您可以使用User注释覆盖这些默认值:

@JoinTable

@ManyToMany(mappedBy = "votedDownBy")
@JoinTable(name="User_Foo_Votedown", 
            joinColumns={@JoinColumn(name="User_ID")}, 
            inverseJoinColumns={@JoinColumn(name="Foo_id")})
private Set<Foo> votedDown =new HashSet<Foo>();

@ManyToMany(mappedBy = "favouritedBy")
@JoinTable(name="User_Foo_Fav", 
            joinColumns={@JoinColumn(name="User_ID")}, 
            inverseJoinColumns={@JoinColumn(name="Foo_id")})
private Set<Foo> favourites = new HashSet<Foo>();

您还可以将@ManyToMany(mappedBy = "votedDown") private Set<User> votedDownBy = new HashSet<User>(); @ManyToMany(mappedBy = "favorites") private Set<User> favouritedBy = new HashSet<User>(); 注释放在mappedBy中,将User放在JoinTable中,因为这是一种对称的双向关系。

答案 1 :(得分:0)

只需将连接表添加到每个映射修复它,foo类现在看起来像这样:

@ManyToMany
@JoinTable(name="user_foo_vote_down")
private Set<User> votedDownBy = new HashSet<User>();

@ManyToMany
@JoinTable(name="user_foo_favourite")
private Set<User> favouritedBy = new HashSet<User>();