StuPointerException
StuPointerException

Reputation: 7267

JPA parent/child relationship

Using JPA (Hibernate) I'm trying to implement the below relationship and was wondering if others have any suggestions about the best approach:

@Entity(name="SOMETHING")
public class Something {
    List<MetaDatum> metaData;
}

@Entity(name="SOMETHING_COMPLETELY_DIFFERENT")
public class SomethingCompletelyDifferent {
    List<MetaDatum> metaData;
}

@Entity(name="META")
public class MetaDatum {

}

Basically it's n completely unrelated objects which each have a collection of common child objects; simple to implement in the object model, slightly more troublesome in the database!

I'm sure this must be a common occurrence but I've had trouble finding any example implementations since I don't really know the right search terms.

Thanks for your time!

Upvotes: 2

Views: 1128

Answers (1)

kostja
kostja

Reputation: 61538

Looks like a case for the @OneToMany annotation on the metaData fields in your Something and SomethingCompletelyDifferent (SCD)entities. Where you go from there depends.

Since Something and SCD do not have a common ancestor, you cannot simply make the relation bidirectional and use a join column.

There are several solutions, so you will have to decide depending on your actual use case.

  • simply stick with the unidirectional relation, if you do not need to traverse from MetaDatum to it's parent entities. The relation will be mapped with join tables by hibernate.

  • make separate MetaDatum1 and MetaDatum2 entities that can have bidirectional relations to their respective parent objects.

  • create a common ancestor for the two parent entities, containing a bidirectional relation to MetaDatum

  • create two entities, each encapsulating a List<MetaDatum>, tailored for a bidirectional relation to your Something and SCD entities

Upvotes: 2

Related Questions