Generic querydsl orderBy dynamic path generation with left joins

后端 未结 1 1598
陌清茗
陌清茗 2021-01-19 01:58

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 {         


        
相关标签:
1条回答
  • 2021-01-19 02:06

    I added now a protoype of the implementation to the test side of Querydsl https://github.com/mysema/querydsl/issues/582

    I will consider a direct integration into Querydsl if this a common use case

    public class OrderHelper {
    
    private static final Pattern DOT = Pattern.compile("\\.");
    
    public static PathBuilder<?> join(JPACommonQuery<?> query, PathBuilder<?> builder, Map<String, PathBuilder<?>> joins, String path) {
        PathBuilder<?> rv = joins.get(path);
        if (rv == null) {
            if (path.contains(".")) {
                String[] tokens = DOT.split(path);
                String[] parent = new String[tokens.length - 1];
                System.arraycopy(tokens, 0, parent, 0, tokens.length - 1);
                String parentKey = StringUtils.join(parent, ".");
                builder = join(query, builder, joins, parentKey);
                rv = new PathBuilder(Object.class, StringUtils.join(tokens, "_"));
                query.leftJoin((EntityPath)builder.get(tokens[tokens.length - 1]), rv);
            } else {
                rv = new PathBuilder(Object.class, path);
                query.leftJoin((EntityPath)builder.get(path), rv);
            }
            joins.put(path, rv);
        }
        return rv;
    }
    
    public static void orderBy(JPACommonQuery<?> query, EntityPath<?> entity, List<String> order) {
        PathBuilder<?> builder = new PathBuilder(entity.getType(), entity.getMetadata());
        Map<String, PathBuilder<?>> joins = Maps.newHashMap();
    
        for (String entry : order) {
            String[] tokens = DOT.split(entry);
            if (tokens.length > 1) {
                String[] parent = new String[tokens.length - 1];
                System.arraycopy(tokens, 0, parent, 0, tokens.length - 1);
                PathBuilder<?> parentAlias = join(query, builder, joins, StringUtils.join(parent, "."));
                query.orderBy(parentAlias.getString(tokens[tokens.length - 1]).asc());
            } else {
                query.orderBy(builder.getString(tokens[0]).asc());
            }
        }
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题