我将下面的代码用于带有JPA标准查询的PostgresDB
public static Specification<EventRecord> findEventRecords(final String id,
final Boolean status,
final Date createdTime, final Date updatedTime, final String userId,
final List<ChannelType> channelType, final List<String> eventType) {
return (root, query, builder) -> {
List<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(builder.and(builder.equal(root.get( TestRecord_.id), id))); //1st param from Rest API
predicates.add(builder.and(builder.equal(root.get( TestRecord_.status),status))); //2nd param from Rest API
predicates.add(builder.and(builder.greaterThanOrEqualTo(root.get( TestRecord_.createdTime), createdTime))); //3rd param from Rest API
predicates.add(builder.and(builder.lessThanOrEqualTo(root.get( TestRecord_.updatedTime), updatedTime))); //4th param from Rest API
if (eventType != null && !eventType.isEmpty()) {
predicates.add(builder.and(builder.equal(root.get( TestRecord_.eventType), eventType))); // gives error saying No value specified for parameter 5.
}
Predicate[] predicatesArray = new Predicate[predicates.size()];
return builder.and(predicates.toArray(predicatesArray));
};
}
}
我尝试使用in和isMember(),但仍然出现错误,如何使用IN子句使用谓词构建查询。
Query :
select * from test_record where (id=? and status = true and created_time = ? and updated_time = ? and event_type IN (value1, value2, value3);
更新
Query That i want to build with Predicates :
select * from test_record where (id=? and status = ? and created_time = ? and updated_time = ? and event_type IN ?;
因此,我在传递任何列表值时收到相同的错误,如何解决这些错误:
org.postgresql.util.PSQLException: No value specified for parameter 5.
at org.postgresql.core.v3.SimpleParameterList.checkAllParametersSet(SimpleParameterList.java:257) ~[postgresql-42.2.2.jar:42.2.2]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:290) ~[postgresql-42.2.2.jar:42.2.2]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441) ~[postgresql-42.2.2.jar:42.2.2]
答案 0 :(得分:0)
一个快速的建议是使用IN谓词创建一个表达式并将其添加到您的查询生成器中。我还没有执行代码,但是下面的代码应该可以工作。
List<String> list = Arrays.asList(new String[]{"SomeValue1", "SomeValue1"});
Expression<String> inExpression = root.get( TestRecord_.eventType);
Predicate inPredicate = inExpression.in(list);
if (eventType != null && !eventType.isEmpty()) {
predicates.add(builder.and(builder.equal(inPredicate)));
}