正如在一些评论中发布的那样,我还需要根据字段名称 creationDateFrom 和 creationDateTo 有不同的行为。为了使它工作,我做了以下工作:
首先,我将@QueryEntity 注释和另外两个字段添加到我的实体类中。字段注释为:
-
@Transient 所以字段不会持久化
-
@Getter(value =
AccessLevel.PRIVATE) 在我们使用 Lombok 时,注释隐藏了
响应正文中的字段
-
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) 负责解析的格式
url查询参数上的日期
@QueryEntity
@Entity
public class MyEntity implements Serializable {
...
@Column(updatable = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private Date creationDate;
@Transient
@Getter(value = AccessLevel.PRIVATE)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private Date creationDateTo;
@Transient
@Getter(value = AccessLevel.PRIVATE)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private Date creationDateFrom;
...
}
然后我将生成querydsl类的方式从JPAAnnotationProcessor更改为QuerydslAnnotationProcessor。这样,使用@Transient 注释的字段仍会在QMyEntity 上生成,但不会持久化。 pom中的插件配置:
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/annotations</outputDirectory>
<processor>com.querydsl.apt.QuerydslAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
最后我扩展了QuerydslBinderCustomizer 并自定义了与creationDateFrom 和creationDateTo 相关的绑定,但在creationDate 上应用了正确的逻辑
@Override
default void customize(QuerydslBindings bindings, QMyEntity root) {
bindings.bind(root.creationDateFrom).first((path, value) ->
root.creationDate.after(value));
bindings.bind(root.creationDateTo).first((path, value) ->
root.creationDate.before(value));
}
通过所有这些,您可以使用一个、两个或一个条件进行日期范围查询:
http://localhost:8080/myentities?creation_date_to=2017-05-08
http://localhost:8080/myentities?creation_date_from=2017-01-01
http://localhost:8080/myentities?creation_date_from=2017-01-01&creation_date_to=2017-05-08