2012-04-24 45 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); 
     } 
     ... 
    } 
    ... 
}