Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate @OneToMany without a separate join table

Consider the following database schema:

create table UserGroup ( id int not null auto_increment, name varchar(200),
    primary key(id));
create table User ( id int not null auto_increment, name varchar(200),
    groupId int not null, primary key(id));

User.groupId = UserGroup.id, so a user can only be a member of one group, but a usergroup can exist of many users. Fine so far, let's make the entities in Hibernate. Here's User:

@Entity
@Table(name = "User")
public class User {

    @Id
    @Column(name="id", nullable = false)
    private Integer id;

    @Column(name="name", length = 200, nullable = true)
    private String name;

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "groupId", nullable = false, insertable=false, updatable=false)
    @ForeignKey(name="FK_GroupId")
    private UserGroup userGroup;

    /* Getters, Setters, toString, equals & hashCode */
}

Here's UserGroup:

@Entity
@Table(name = "UserGroup")
public class UserGroup {

    @Id
    @Column(name="id", nullable = false)
    private Integer id;

    @Column(name="name", length = 200, nullable = true)
    private String name;

    @OneToMany(fetch=FetchType.EAGER)
    private List<User> users;

    /* Getters, Setters, toString, equals & hashCode */
}

Now I'll get an error "Table mydb.usergroup_user' doesn't exist" because it expects a join-table. My data structure is "set in stone" due to interoperability with other applications that this application will replace, so I won't be making a join-table. Also, it should not be needed. How can I make a List<User> users that simply is a list of User where User.groupId == UserGroup.Id?

like image 336
niklassaers Avatar asked Aug 21 '09 07:08

niklassaers


1 Answers

I think you need the mappedBy="UserGroup" in the @OneToMany annotation.

like image 152
Brian Yarger Avatar answered Nov 09 '22 14:11

Brian Yarger