1

I am having some difficulty using hibernate to select using join tables that represent a many to many.

I have the following three tables (bold represents the links / keys)

User {id, username, password}

Group {id, name, scpid}

Join table = Member {id, groupId, username}

So I have the scenario that in my DAO for user and group i want to get the available groups and the available members respectively.

This means I need to provide the mapping but am unsure how to do this. So far to get the groups for a user i have tried something like this but it complains about a duplicate username

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "member", joinColumns = {@JoinColumn(name = "username", nullable = false, updatable = false)}, inverseJoinColumns = {@JoinColumn(name = "username", nullable = false, updatable = false)})
public Set<Group> getGroups()
{
    return userGroups;
}

public void setGroups(Set<Group> userGroups)
{
    this.userGroups = userGroups;
}

Can anyone help me in identifying how I would solve this please?

Thanks

Biscuit128
  • 5,218
  • 22
  • 89
  • 149
  • It should be `inverseJoinColumns = {@JoinColumn(name = "groupId")}` to indicate that the participating column for the referenced entity in the join table is named `groupId` (according to your example). – manish Jul 22 '15 at 15:33
  • why would it be group id? to join the tables it would be on user.username and join on member.username? – Biscuit128 Jul 23 '15 at 11:10
  • Run your code and look at the SQL query that is generated. That will answer your question of why the suggested change needs to be made to generate the correct query. – manish Jul 23 '15 at 11:44
  • The correct annotation should be `@JoinTable(name = "member", joinColumns = {@JoinColumn(name = "username", referencedColumnName = "username", nullable = false, updatable = false)}, inverseJoinColumns = {@JoinColumn(name = "groupId", nullable = false, updatable = false)})`. See the Javadocs for `@ManyToMany` for details. – manish Jul 23 '15 at 11:48

1 Answers1

3

According to provided code snippet both @JoinColumn's name attribute is having username as value.

AimZ
  • 526
  • 2
  • 9
  • why would it not be username? to join the tables it would be on user.username and join on member.username? – Biscuit128 Jul 23 '15 at 11:10
  • The `@JoinTable` annotation is used to create the **link table** and `@JoinColumn` annotation is used to _refer_ the linking columns in both the tables. In this case, first `@JoinColumn` should refer to current table (User) id and second should refer to the group table id. If you are not familiar with JPA/Hibernate mappings, please check [this](http://www.mkyong.com/hibernate/hibernate-many-to-many-relationship-example-annotation/) basic example. Moreover, your link table has an extra column so `@JoinTable` won't work. Check this [answer](http://stackoverflow.com/a/5127262) for details. – AimZ Jul 23 '15 at 12:19