I am using:
Spring 3.2
Hibernate 4.1.9
I need to map, with JPA, three classes. Class A has a ManyToMany relationship with Class B. A unique combination of Class A and Class B need to own a collection of Class C.
Table A
foo
id | name
Table B
bar
id | name
Table C
data
id | xrefId
Join Table — Unique Key on (fooId,barId)
xref
id | fooId | barId
Altering the existing data structure is not an option.
Edit 1:
Goal: Load a Foo, get its collection of Bars. From each Bar, get its (their!) collection of Data.
Class A
@Entity
public class Foo {
@Id
private UUID id;
@ManyToMany(optional = false)
@JoinTable(name = "xref",
joinColumns = { @JoinColumn(name = "fooId") },
inverseJoinColumns = { @JoinColumn(name = "barId") })
private List<Bar> lstBar = new ArrayList<Bar>();
}
Class B
public class Bar {
@Id
private UUID id;
@ManyToMany(mappedBy = "lstBar")
private List<Foo> lstFoo = new ArrayList<Foo>();
}
Class C
public class Data {
@Id
private UUID id;
}
Just KISS. Make another class Xref, which contains
id,foo,barandSet<Data>fields. Make a DAO method to find an Xref using two parametersfooandbar(implement it with a simple HQL). The unique requirement could be achieved by an unique constraint in the database.It doesn’t look good trying to express it just by the class hierarchy, better to use DAOs.