如何在Hibernate中进行多重关系?

时间:2017-12-13 11:02:50

标签: java database hibernate annotations mapping

大家好!对不起,我需要一些帮助。我的db是looking this way,我尝试在Java中使用Hibernate。

但是我不明白我需要如何用这么多不同的表来注释这种关系。 它是我的Abiturient表的一部分。

@Entity
@Table (name = "abiturient",
            uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})

public class Abiturient {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, unique = true, length = 11)
    @ManyToOne
    private Long id;

    @Column
    private Date data_narodjennya;

    @Column
    private Integer city_village;

它是我的nomer_telefonu表的一部分

@Entity
@Table(name = "nomer_telefonu")
public class NomerTelefonu {
    @Id
    @Column(name = "nomer_tel_id", nullable = false, unique = true, length = 11)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long nomer_tel_id;

    @Column(name = "nomer")
    private String nomer;

    @Column(name = "id")
    @OneToMany(fetch = FetchType.LAZY)
    private Set<Abiturient> id;

我不认为一切都是正确的,`每当我尝试解决问题时,我会收到错误并需要其他类型。

1 个答案:

答案 0 :(得分:1)

使用@OneToMany双向关系。

@Entity
public class Abiturient {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy = "abiturent")
    private List<NomerTelefonu> phones = Lists.newArrayList();

} 

@Entity
public class NomerTelefonu{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "nomer_tel_id")
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private Abiturient abiturent;

} 
来自番石榴的

Lists.newArrayList()。这是工作映射。始终使用最简单的版本进行试验。

what is @JoinColumn and how it is used in Hibernate

您可以使用此项目在单元测试中使用映射:

https://github.com/v-ladynev/hibernate-experimental