简体   繁体   中英

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 ?

我认为你需要@OneToMany注释中的mappedBy="UserGroup"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM