gpt4 book ai didi

java - 完全动态地创建 JPA 标准

转载 作者:搜寻专家 更新时间:2023-10-31 20:14:45 25 4
gpt4 key购买 nike

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

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

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

但我不想那样做!因为我在容器中使用了泛型!你有想法吗?

最佳答案

只要您的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);
}
...
}
...
}

关于java - 完全动态地创建 JPA 标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10296870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com