6

通常我是 Hibernate 用户,对于我的新项目,我们使用 JPA 2.0。

我的 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

1 回答 1

5

只要你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);
        } 
        ...
    }
    ...
}
于 2012-04-24T11:37:01.100 回答