Reputation: 2672
I have a class Person and each person can have documents with a specific language. The Person and Document classes are linked with a Many-To-Many relationship.
My Java code looks like this:
@Table(name="person")
public class Person {
@Id
@Column(name="id")
private Long id;
@Column(name="name")
private String name;
@ManyToMany(targetEntity=Document.class)
@JoinTable(name="person_document",
joinColumns={
@JoinColumn(name="person_id")
},
inverseJoinColumns={
@JoinColumn(name="document_id")
}
)
private List<Document> documents;
// getter and setter ....
}
public class Document {
@Id
@Column(name="id")
private Long id;
@Column(name="language")
private String language;
// getter and setter ...
}
NOTE: I'm using Hibernate 3 here.
I want to create a query which gives me back all persons with documents only in a specific language, say english.
My first attempt was following code
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.createCriteria(Person.class)
.createAlias("documents", "d")
.add(Restrictions.eq("d.language", "english")
.list();
This code lists just the people who have documents in english but I want all persons but only documents in english for each person.
For example:
I want to get listed:
Does that make sense? And if so how would a Hibernate query for such as query look like.
As that is really hard to get I'm thinking about this is the wrong way to do it but I don't know any other way to do it.
I appreciate your help!
Upvotes: 1
Views: 2090
Reputation: 921
You should query vise versa. That means you should load documents which are in English and from that document objects you can get the persons.
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.createCriteria(Documentn.class)
.createAlias("documents", "d")
.add(Restriction.eq("d.language", "english")
.list();
Upvotes: 2