7

我有接下来的几个豆子:

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 的情况下解决此问题的想法?

谢谢!

4

5 回答 5

20

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

于 2013-09-11T01:20:14.467 回答
3

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);
于 2016-03-04T06:05:02.273 回答
2

AliasToBeanNestedResultTransformer 不处理嵌套多级 DTO,所以我重写了一个处理 n 级 dto。

希望这可以帮助。

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));
        }

    }

}

}

于 2016-05-02T14:21:29.367 回答
2

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

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

这并不意味着 Hibernate 正在寻找public String getAddressName() {}. 相反,它会寻找具有不可能的“setAddress.name”名称的设置器。

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

然后,只需在“MyEntity”根对象上添加一个设置器:“setAddressName”。

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

缺点是它用额外的方法“弄脏”了你的对象。

也张贴在这里

于 2017-07-26T08:20:42.970 回答
1

尝试创建一个别名 likecriterio.createAlias("address", "add");然后将您的属性编辑为 like Arrays.asList("add.number","add.zipcode", "add.town")

希望这可以帮助。

于 2013-09-10T08:16:08.997 回答