The query of the combined spring data specification has multiple connections on the same table
•
Java
Sorry, if my terminology is incorrect
We use spring data, jparepositories and conditional query as methods to query database data
I have a problem. When I combine two specifications in the following code example, for example, when I use hastimezone and hascity in hascityandtimezone, it will be connected twice on the same table, so the following query looks like
select * from Staff,Location,Location@H_404_7@有没有办法让这两个规范使用相同的连接而不是每个定义它们自己的连接基本相同?
对不起代码可能不完整我只是想展示一个简单的例子.
class Staff { private Integer id; private Location location; } class Location { private Integer id; private Integer timeZone; private Integer city; } class StaffSpecs { public static Specification<Staff> hasTimeZone(Integer timeZone) { return new Specification<Staff>() { @Override public Predicate toPredicate(Root<Staff> root,CriteriaQuery<?> query,CriteriaBuilder cb) { Path<Integer> timeZonePath = root.join(Staff_.location).get(Location_.timeZone); return cb.equal(timeZonePath,timeZone); } } } public static Specification<Staff> hasCity(Integer city) { return new Specification<Staff>() { @Override public Predicate toPredicate(Root<Staff> root,CriteriaBuilder cb) { Path<Integer> cityPath = root.join(Staff_.location).get(Location_.city); return cb.equal(cityPath,city); } } } public static Specification<Staff> hasCityAndTimeZone(Integer city,Integer timeZone) { return where(hasCity(city)).and(hasTimeZone(timeZone)); } }@H_404_7@Solution
Unfortunately, there is no out of the box way Spring data uses queryutils internally Some connections in getorcreatejoin (...) are reused You can find connections that may already exist at the root and reuse them where appropriate:
private static Join<?,?> getOrCreateJoin(From<?,?> from,String attribute) { for (Join<?,?> join : from.getJoins()) { boolean sameName = join.getAttribute().getName().equals(attribute); if (sameName && join.getJoinType().equals(JoinType.LEFT)) { return join; } } return from.join(attribute,JoinType.LEFT); }@H_404_7@请注意,这只有在我们有效地知道自己添加哪些连接时才有效.使用规格时你也应该这样做,但我只是想确保没有人认为这是所有情况下的通用解决方案.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码