2012-04-24 51 views
4

通常我是Hibernate用户,对于我的新项目,我们使用JPA 2.0。完全动态创建JPA标准

我的DAO收到一个带有泛型的Container。

public class Container<T> { 
    private String fieldId; // example "id" 
    private T value;   // example new Long(100) T is a Long 
    private String operation; // example ">" 

    // getter/setter 
} 

以下行不会编译:

if (">".equals(container.getOperation()) { 
    criteriaBuilder.greaterThan(root.get(container.getFieldId()), container.getValue()); 
} 

因为我必须指定这样的类型:

if (">".equals(container.getOperation()) { 
    criteriaBuilder.greaterThan(root.<Long>get(container.getFieldId()), (Long)container.getValue()); 
} 

但我并不想这样做!因为我在我的容器中使用通用的! 你有想法吗?

回答

4

只要你TComparable(必须为greaterThan),你应该能够做到像下面这样:

public class Container<T extends Comparable<T>> { 
    ... 
    public <R> Predicate toPredicate(CriteriaBuilder cb, Root<R> root) { 
     ... 
     if (">".equals(operation) { 
      return cb.greaterThan(root.<T>get(fieldId), value); 
     } 
     ... 
    } 
    ... 
}