完全动态创建JPA标准
通常我是Hibernate用户,对于我的新项目,我们使用JPA 2.0。
我的DAO收到一个带有通用的Container。
public class Container { 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.get(container.getFieldId()), (Long)container.getValue()); }
但我不想那样做! 因为我在容器中使用通用! 你有个主意吗?
只要你的T
是Comparable
(它是greaterThan
必需的),你应该能够做如下的事情:
public class Container> { ... public Predicate toPredicate(CriteriaBuilder cb, Root root) { ... if (">".equals(operation) { return cb.greaterThan(root.get(fieldId), value); } ... } ... }