Hibernate - 从模式创建类

时间:2016-07-08 06:49:35

标签: java hibernate class schema

我创建了类:

@Table(name = "FILE_SET")
@Entity
public class FileSet
{
    @Id
    @Column(name = "FileSetId")
    private final long fileSetId;

    @Column(name = "FileSetState")
    private final int fileSetState;

    @OneToMany(targetEntity = Variables.class)
    private final Set<Variables> variables;
}

@Entity
@Table(name = "VARIABLES")
public class Variables
{
    @Id
    @Column(name = "VariablesId")
    private final int variablesId;

    @ManyToOne(targetEntity = FileSet.class)
    @JoinColumn(name = "CurrentFileSetId")
    private final long currentFileSetId;

    @Column(name = "CurrentDevicesDictId")
    private final long currentDevicesDictId;
}

此代码是crating表: https://zapodaj.net/b18d0afb396e5.png.html

但是我想只有“Variables”和“FileSet”,其中Variables中的CurrentFileSetId是来自FileSet的外键。我究竟做错了什么?我第一次使用hibernate。

2 个答案:

答案 0 :(得分:2)

OneToMany方添加@JoinColumn(name = "CurrentFileSetId")

@OneToMany(targetEntity = Variables.class)
@JoinColumn(name = "CurrentFileSetId")
private final Set<Variables> variables;

所以不是创建JoinTable,而是创建一个FK。

以上答案对单向关联有效。

因此,为了使答案完整,即在双向关联的情况下,以下应该是代码:

@ManyToOne(targetEntity = FileSet.class)
@JoinColumn(name = "CurrentFileSetId")
private final long currentFileSetId;

and 

@OneToMany(targetEntity = Variables.class, mappedBy = "currentFileSetId") //this is the field name in FileSet class.
private final Set<Variables> variables;

基本上,注释@JoinColumn表示该实体是关系的所有者。而在mappedBy中,我们提供拥有该关系的字段。

答案 1 :(得分:1)

我认为,@ eatSleepCode的答案是正确的。但我想介绍一种更常见的Hibernate方法。

您永远不应该使用像currentFileSetId这样的普通外键字段 - 而是使用与实体的关联。而且您不需要使用targetEntity = Variables.class,Hibernate会将其用作默认值。

@Table(name = "FILE_SET")
@Entity
public class FileSet
{
    @Id
    @Column(name = "FileSetId")
    private final long fileSetId;

    @Column(name = "FileSetState")
    private final int fileSetState;

    @OneToMany(mappedBy = "currentFileSet")
    private final Set<Variables> variables;

}

@Entity
@Table(name = "VARIABLES")
public class Variables
{
    @Id
    @Column(name = "VariablesId")
    private final int variablesId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "CurrentFileSetId")
    private FileSet currentFileSet;

}

如果您不想与FileSet部分Variables关联(仍然将CurrentFileSetId作为外键):

@Table(name = "FILE_SET")
@Entity
public class FileSet
{
    @Id
    @Column(name = "FileSetId")
    private final long fileSetId;

    @Column(name = "FileSetState")
    private final int fileSetState;

    @OneToMany
    @JoinColumn(name = "CurrentFileSetId")
    private final Set<Variables> variables;

}

@Entity
@Table(name = "VARIABLES")
public class Variables
{
    @Id
    @Column(name = "VariablesId")
    private final int variablesId;

}