Create a JPA Criteria fully dynamically

谁都会走 提交于 2019-12-01 18:20:00

问题


Usually I'm a Hibernate user and for my new project we use JPA 2.0.

My DAO receives a Container with a generic.

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
}

The following lines won't compile:

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

Because I must specify the type like this:

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

But I don't want to do that! Because I use a generic in my container! Have you an idea?


回答1:


As long as your T is Comparable (it's required for greaterThan), you should be able to do something like the following:

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


来源:https://stackoverflow.com/questions/10296870/create-a-jpa-criteria-fully-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!