In my project, I'm trying to implement some Entities with one parent and multiple children by JPA & Hibernate like this:
/********** parent type **********/
@Entity
@Table(name = "t_parent")
public class Parent {
@Id
@Column(name = "f_id")
private Long id;
}
/********** children types **********/
@Entity
@Table(name = "t_child_a")
public class ChildA {
@Id
@Column(name = "f_id")
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "f_parent")
private Parent parent;
}
@Entity
@Table(name = "t_child_b")
public class ChildB {
@Id
@Column(name = "f_id")
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "f_parent")
private Parent parent;
}
Because there will be more Children Types in the future, so relationships are only declared on the children side by annotation "ManyToOne", and there is no corresponding "OneToMany" on the parent side.
When delete a parent entity, any exist relationship will cause ConstraintViolationException from database.
My purpose is to find out that is there any children instance who has referenced to a specific parent instance, so i can give a clear and meaningful message to user, or any best practices for such situation?