I have a list of projects and a list of customers. A project can be for one customer and every customer can have many projects. So it's a simple 1:n relationship where the project is the owning side.
Simplified to the essential it is
@Entity
public class Project {
@Id
long id;
@ManyToOne(optional = true)
@JoinColumn(name = "customer", nullable = true, updatable = true)
Customer customer;
}
@Entity
public class Customer {
@Id
long id;
}
When I load a list of projects, I want to retrieve the customers efficiently at the same time. This is not the case. There is one single query for the projects and then for every distinct customer that is encountered a separate query is issued.
So say I have 100 projects that are assigned to 50 different customers. This would result in one query for the projects and 50 queries for the customers.
This quickly adds up and for large project/customer lists our application gets rather slow. Also this is just one example. All our entities with relationships are affected by this behavior.
I already tried @Fetch(FetchMode.JOIN)
on the customers
field as suggested here but it does nothing and FetchMode.SUBQUERY
is not applicable according to Hibernate:
org.hibernate.AnnotationException: Use of FetchMode.SUBSELECT not allowed on ToOne associations
How can I fix this problem?