I've run into a problem while using JPA with Querydsl and Hibernate for data storage management. The sample model is as follows:
@Entity
public class User {
....
@ManyToOne
@JoinColumn(name = "CATEGORY_ID")
private Category category;
}
@Entity
public class Category {
..
private String acronym;
@OneToMany(mappedBy = "category")
List<User> userList;
}
In my Spring MVC webapp I have a search form with User parameters and orderBy select. The orderBy select can be either User property or Category property. The orderBy parameters are stored as Map (f.e. {"login" : "adm", {"firstName" : "John"}. The search function receives the search parameters (as string) and the map above with order specification. The simplified code for ordering is as follows:
Map<String, String> orderByMap = new HashMap<String, String>();
orderByMap.put("firstName", "asc");
orderByMap.put("unit.acronym", "desc");
PathBuilder<User> pbu = new PathBuilder<User>(User.class, "user");
....
for (Map.Entry<String, String> order : orderByMap.entrySet())
{
// for simplicity I've omitted asc/desc chooser
query.orderBy(pbu.getString(order.getKey()).asc());
}
The problem starts when I want to introduce sorting by Category's parameter, like {"category.acronym", "desc"}. As explained here, the above code will make querydsl to use cross join with Category table and omitt the Users without Categories, which is not expected behavior.
I know, I have to introduce the left join with Categories and use the alias for the sorting to make it work, hovewer I'm looking for efficient way to do it dynamically. Stripping each String looking for category or any other entity (like "user.category.subcategory.propetry") will introduce a lot of ugly code and I'd rather not do that.
I'd appreciate the help with some more elegant solution.