java 没有单独的连接表的休眠@OneToMany

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1310603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:04:36  来源:igfitidea点击:

Hibernate @OneToMany without a separate join table

javahibernatejpajoinentity-relationship

提问by niklassaers

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:

User.groupId = UserGroup.id,所以一个用户只能是一个组的成员,但一个用户组可以存在多个用户。到此为止,让我们在 Hibernate 中创建实体。这是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:

这是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> usersthat simply is a list of User where User.groupId == UserGroup.Id?

现在我会得到一个错误,"Table mydb.usergroup_user' doesn't exist"因为它需要一个连接表。由于与该应用程序将替换的其他应用程序的互操作性,我的数据结构是“一成不变的”,因此我不会制作连接表。此外,它不应该被需要。我怎样才能制作一个List<User> users简单的用户列表User.groupId == UserGroup.Id

回答by Brian Yarger

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

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