How to create entity relationship for following scenario in Spring data JPA?

时间:2016-07-11 19:08:44

标签: hibernate spring-data-jpa

@Entity
public class A {
 @column("ID")
 private Long id;
}

@Entity
public class B {
 @column("ID")
 private Long id;
}

@Entity
public class C {
 @column("ID")
 private Long id;

 @column("A_ID")
 private Long aID;

 @column("B_ID")
 private Long bID;
}

In C entity following insert are possible

ID A_ID  B_ID
 1   1     1
 2   2     1
 3   3     1
 4   1     2
 5   2     2
 6   3     2

In above case i want to get parent entity(A or B) from child entity(C)

e.g

C c=crepository.findByID(6);
A a=c.getA();
B b=c.getB();

How to create relationship in above Entity's? I hope it is achievable using Spring data JPA.

1 个答案:

答案 0 :(得分:0)

Something like this leveraging the @OneToOne annotation should do it:

@Entity
public class A {
    @Column("ID")
    private Long id;

    //other columns, getters, and setters
}

@Entity
public class B {
    @Column("ID")
    private Long id;

    //other columns, getters, and setters
}

@Entity
public class C {
    @column("ID")
    private Long id;

    @OneToOne
    @JoinColumn(name = "A_ID", referencedColumnName  = "ID")
    private A a;

    @OneToOne
    @JoinColumn(name = "B_ID", referencedColumnName  = "ID")
    private B b;

    //other columns, getters, and setters
}