Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring DATA JPA example for multiple foreign keys in a single entity

Below is my table design. can someone explain me how to configure my entity using spring data jpa?

PARENT_TABLE(
id primary key,
name
)

SECOND_CHILD_TABLE(
id primary key,
second_child_name,
parent_id references id on  parent_table,
first_child_id references id on first_child_table
)

FIRST_CHILD_TABLE(
id primary key,
first_child_name,
parent_id references id on  parent_table
)
like image 646
user3560205 Avatar asked Jun 27 '14 06:06

user3560205


1 Answers

If you are asking for JPA Mapping then should be as following.

@Entity
@Table(name="parent_table")
public class Parent {
    @Id
    @Column(name="ID", nullable=false, unique=true)
    // Require Generator config
    private Long id;

    @Column(name="NAME", nullable=false)
    private String name;
}

@Entity
@Table(name="first_child_table")
public class FirstChild {
    @Id
    @Column(name="ID", nullable=false, unique=true)
    // Require Generator config
    private Long id;

    @Column(name="FIRST_CHILD_NAME", nullable=false)
    private String name;

    @OneToOne
    @JoinColumn(name="parent_id", referencedColumnName="ID")
    private Parent parent;
}

@Entity
@Table(name="second_child_table")
public class SecondChild {
    @Id
    @Column(name="ID", nullable=false, unique=true)
    // Require Generator config
    private Long id;

    @Column(name="SECOND_CHILD_NAME", nullable=false)
    private String name;

    @OneToOne
    @JoinColumn(name="parent_id", referencedColumnName="ID")
    private Parent parent;

    @OneToOne
    @JoinColumn(name="first_child_id", referencedColumnName="ID")
    private FirstChild firstChild;
}
like image 101
shazin Avatar answered Sep 24 '22 20:09

shazin