完全动态创建一个JPA标准 [英] Create a JPA Criteria fully dynamically

查看:87
本文介绍了完全动态创建一个JPA标准的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

  public class Container< T> {
private String fieldId; //示例id
私人T值; //示例new Long(100)T是一个Long
私有字符串操作; //示例>

// 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());
}



但我不想这么做!因为我在容器中使用了一个泛型!
你有想法吗? / p>

解决方案

只要您的 T (它是 greaterThan 所必需的),您应该可以执行以下操作:

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


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?

解决方案

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

这篇关于完全动态创建一个JPA标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆