在Hibernate中使用Transformers.aliasToBean填充子bean

时间:2013-09-10 07:43:49

标签: java hibernate

我有接下来几个豆子:

Address {
    String name;
    String number;
    String zipcode;
    String town;
}

MyEntity {
    Address address;
    String value1;
    String value2;
}

我正在尝试进行下一个Hibernate查询:

private final List<String> propertiesDistinct = Arrays.asList("address.name");
private final List<String> properties = Arrays.asList("address.number",
        "address.zipcode", "address.town")

ProjectionList projectionList = Projections.projectionList();

if (propertiesDistinct != null) {
    ProjectionList projectionListDistinct = Projections.projectionList();
for (String propertyDistinct : propertiesDistinct)
         projectionListDistinct.add(Projections.property(propertyDistinct).as(propertyDistinct));

    projectionList.add(Projections.distinct(projectionListAgrupar));
}

if (properties != null)
    for (String property : properties)
         projectionList.add(Projections.property(property).as(property));
criterio.setProjection(projectionList);

// MORE FILTERS ON MyEntity FIELDS
//... criterio.add(Restrinctions...);

// I want to recover the results on my bean MyEntity so I don't have to create a new one
criterio.setResultTransformer(Transformers.aliasToBean(MyEntity.class));

问题:

Caused by: org.hibernate.PropertyNotFoundException: Could not find setter for address.name on class com.entities.MyEntity

我知道Hibernate正在寻找类似的东西:

public String getAddressName() {} // This should be in MyEntity

而不是:

public String getName() {} // In my Address bean

关于如何在不创建新bean的情况下解决这个问题的想法?

谢谢!

5 个答案:

答案 0 :(得分:18)

我写了一个可以解决问题的ResultTransformer。它的名字是AliasToBeanNestedResultTransformer,请在github上查看。

答案 1 :(得分:2)

Github中提供的代码工作正常,但import对于新版本的hibernate有变化。如下。

org.hibernate.property.PropertyAccessor替换为org.hibernate.property.access.spi.PropertyAccess

org.hibernate.property.PropertyAccessorFactory替换为org.hibernate.property.access.internal.PropertyAccessStrategyBasicImpl

所以你已经改变了

的代码
PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor("property");
accessor.getSetter(resultClass, (String)subclassToAlias.get(subclass).get(2)).set(root, subObject, null);

PropertyAccess propertyAccess = PropertyAccessStrategyBasicImpl.INSTANCE.buildPropertyAccess(resultClass, (String)subclassToAlias.get(subclass).get(2));
propertyAccess.getSetter().set(root, subObject, null);

答案 2 :(得分:2)

AliasToBeanNestedResultTransformer不处理嵌套的多级DTO,所以我重新编写了一个处理n级dtos的文件。

希望这会有所帮助。

public class AliasToBeanNestedMultiLevelResultTransformer extends AliasedTupleSubsetResultTransformer {
private static final long serialVersionUID = -8047276133980128266L;

public boolean isTransformedValueATupleElement(String[] aliases, int tupleLength) {
    return false;
}

private boolean initialized;
private Class<?> resultClass;
private Map<String,Class<?>> clazzMap = new HashMap<>();
private Map<String,Setter> settersMap = new HashMap<>();

public AliasToBeanNestedMultiLevelResultTransformer(Class<?> resultClass) {
    this.resultClass = resultClass;
}

public Object transformTuple(Object[] tuples, String[] aliases) {

    Map<String,Object> nestedObjectsMap = new HashMap<>();

    Object result;
    try {
        result = resultClass.newInstance();

        if (!initialized){
            initialized = true;
            initialize(aliases);
        }

        for (int a=0;a<aliases.length;a++){

            String alias = aliases[a];
            Object tuple = tuples[a];

            Object baseObject = result;

            int index = alias.lastIndexOf(".");
            if(index>0){
                String basePath = alias.substring(0, index);
                baseObject = nestedObjectsMap.get(basePath);
                if (baseObject == null){
                    baseObject = clazzMap.get(basePath).newInstance();
                    nestedObjectsMap.put(basePath, baseObject);
                }
            }

            settersMap.get(alias).set(baseObject, tuple,null);

        }

        for (Entry<String,Object> entry:nestedObjectsMap.entrySet()){
            Setter setter = settersMap.get(entry.getKey());
            if (entry.getKey().contains(".")){

                int index = entry.getKey().lastIndexOf(".");
                String basePath = entry.getKey().substring(0, index);
                Object obj = nestedObjectsMap.get(basePath);

                setter.set(obj, entry.getValue(), null);
            }
            else{
                setter.set(result, entry.getValue(), null);
            }
        }

    }catch ( InstantiationException | IllegalAccessException e) {
        throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() );
    }

    return result;
}


private void initialize(String[] aliases) {

    PropertyAccessor propertyAccessor = new ChainedPropertyAccessor(
            new PropertyAccessor[] {
                    PropertyAccessorFactory.getPropertyAccessor( resultClass, null ),
                    PropertyAccessorFactory.getPropertyAccessor( "field" )
            }
    );

    for (int a=0;a<aliases.length;a++){

        String alias = aliases[a];

        Class<?> baseClass = resultClass;

        if (alias.contains(".")){

            String[] split = alias.split("\\.");

            StringBuffer res = new StringBuffer();

            for (int i=0;i<split.length;i++){

                if (res.length()>0) res.append(".");

                String item = split[i];
                res.append(item);

                String resString = res.toString();

                if (i==split.length-1){
                    clazzMap.put(resString,baseClass);
                    settersMap.put(resString, propertyAccessor.getSetter(baseClass, item));
                    break;
                }

                Class<?> clazz = clazzMap.get(resString);
                if (clazz==null){
                    clazz = propertyAccessor.getGetter(baseClass,item).getReturnType();
                    settersMap.put(resString, propertyAccessor.getSetter(baseClass, item));
                    clazzMap.put(resString,clazz);
                }
                baseClass = clazz;
            }
        }
        else{
            clazzMap.put(alias, resultClass);
            settersMap.put(alias, propertyAccessor.getSetter(resultClass, alias));
        }

    }

}

}

答案 3 :(得分:2)

我的解决方案非常基础。它不像正确的结果变换器那么干净,但是当你需要对一些属性进行快速投影时,它非常有用。

如果你得到Could not find setter for address.name on class com.entities.MyEntity

这并不意味着Hibernate正在寻找public String getAddressName() {}。相反,它会寻找一个带有不可能的setter.name&#34;名。

而不是.add(Projections.property("address.name"),"address.name"))键入一个正确的setter名称作为.add()方法的第二个参数,如下所示.add(Projections.property("address.name"),"addressName"))

然后,只需在你的&#34; MyEntity&#34;上添加一个setter root对象:&#34; setAddressName&#34;。

public void setAddressName(String addressName) {
  this.address= (this.address==null) ? new Address() : address;
  this.address.setName(addressName);
}

缺点是它的污垢&#34;你的对象有额外的方法。

同时发布了here

答案 4 :(得分:1)

尝试创建criterio.createAlias("address", "add");之类的别名,然后将您的属性修改为Arrays.asList("add.number","add.zipcode", "add.town")

希望这有帮助。