I set up a Database Application with Spring an Hibernate and I’m using a Many-To-Many-Relationship.
Here’s the code:
Author.java
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name = "writes", joinColumns = {@JoinColumn(name = "authorId")}, inverseJoinColumns = {@JoinColumn(name = "publicationId")})
private Set<Publication> publications = new HashSet<Publication>();
Publication.java
@ManyToMany(mappedBy = "publications")
private Set<Author> authors = new HashSet<Author>();
these lines of code generate a connection-table named writes, but when I try to run a query over all Tables int gives me the error, named above.
this is the method, that schould run the query:
@Transactional
public List<Author> findAuthorByLastname(String lastName) {
String hql = "from Author a, Publication p, writes w where a.id = w.authorId and p.id = w.publicationId and a.lastname = :lastName";
Query q = sessionFactory.getCurrentSession().createQuery(hql);
q.setParameter("lastName", lastName);
List<Author> result = q.list();
return result;
}
You don’t need to mention connection table explicitly in HQL queries (moreover, you even cannot mention them – only mapped entities). You need to use
joinon mapped relationships instead.Also, it’s not quite clear what you want to achieve.
If you want to fetch
Authors with eagerly filled collections of theirPublications in one query, usejoin fetch:If you want to fetch a list of pairs (
Author,Publication), use regularjoin: