There’s an Entity Class “A”. Class A might have children of the same type “A”. Also “A” should hold it’s parent if it is a child.
Is this possible? If so how should I map the relations in the Entity class?
[“A” has an id column.]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, this is possible. This is a special case of the standard bidirectional
@ManyToOne/@OneToManyrelationship. It is special because the entity on each end of the relationship is the same. The general case is detailed in Section 2.10.2 of the JPA 2.0 spec.Here’s a worked example. First, the entity class
A:Here’s a rough
main()method that persists three such entities:In this case, all three entity instances must be persisted before transaction commit. If I fail to persist one of the entities in the graph of parent-child relationships, then an exception is thrown on
commit(). On Eclipselink, this is aRollbackExceptiondetailing the inconsistency.This behavior is configurable through the
cascadeattribute onA‘s@OneToManyand@ManyToOneannotations. For instance, if I setcascade=CascadeType.ALLon both of those annotations, I could safely persist one of the entities and ignore the others. Say I persistedparentin my transaction. The JPA implementation traversesparent‘schildrenproperty because it is marked withCascadeType.ALL. The JPA implementation findssonanddaughterthere. It then persists both children on my behalf, even though I didn’t explicitly request it.One more note. It is always the programmer’s responsibility to update both sides of a bidirectional relationship. In other words, whenever I add a child to some parent, I must update the child’s parent property accordingly. Updating only one side of a bidirectional relationship is an error under JPA. Always update both sides of the relationship. This is written unambiguously on page 42 of the JPA 2.0 spec: