Complex Hibernate Projections

前端 未结 4 756
野的像风
野的像风 2020-12-18 08:06

I want to ask, it is possible that I create query projections and criterion for more than one level deep? I have 2 model classes:

@Entity  
@Table(name = \"p         


        
4条回答
  •  难免孤独
    2020-12-18 08:31

    Thanks Sami Andoni. I was able to use your AliasToBeanNestedResultTransformer with a minor modification to suit my situation. What I found was that the nested transformer did not support the scenario where the field is in a super class so I enhanced it to look for fields up to 10 levels deep in the class inheritance hierarchy of the class you're projecting into:

        public Object transformTuple(Object[] tuple, String[] aliases) {
    
            ...
    
    
                    if (alias.contains(".")) {
                        nestedAliases.add(alias);
    
                        String[] sp = alias.split("\\.");
                        String fieldName = sp[0];
                        String aliasName = sp[1];
    
                        Class subclass = getDeclaredFieldForClassOrSuperClasses(resultClass, fieldName, 1);
    ...
    }
    

    Where getDeclaredFieldForClassOrSuperClasses() is defined as follows:

    private Class getDeclaredFieldForClassOrSuperClasses(Class resultClass, String fieldName, int level) throws NoSuchFieldException{
        Class result = null;
        try {
            result = resultClass.getDeclaredField(fieldName).getType();
        } catch (NoSuchFieldException e) {
            if (level <= 10){
            return getDeclaredFieldForClassOrSuperClasses(
                    resultClass.getSuperclass(), fieldName, level++);
            } else {
                throw e;
            }
        }
        return result;
    }
    

    My Hibernate projection for this nested property looked like this:

    Projections.projectionList().add( Property.forName("metadata.copyright").as("productMetadata.copyright"));
    

    and the class I am projecting into looks like this:

    public class ProductMetadata extends AbstractMetadata {
    ...
    }
    
    public abstract class AbstractMetadata {
    ...   
       protected String copyright;
    ...
    }
    

提交回复
热议问题