Reputation: 101
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
)
Upvotes: 6
Views: 28642
Reputation: 13481
@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;
@OneToMany(orphanRemoval = true, cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
@JoinColumn(name = "candidacy_id", nullable = false)
@Getter
@Setter
private List<FirstChild> firstChild = new ArrayList<>();
@OneToMany(orphanRemoval = true, cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
@JoinColumn(name = "candidacy_id", nullable = false)
@Getter
@Setter
private List<SecondChild> secondChild = new ArrayList<>();
}
@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;
@ManyToOne
@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;
@ManyToOne
@JoinColumn(name="parent_id", referencedColumnName="ID")
private Parent parent;
}
And for the repository
@Repository
public interface ParentRepository extends CrudRepository<Parent, Integer> {
}
Upvotes: 4
Reputation: 21923
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;
}
Upvotes: 7