正如在某个评论中发布的那样,我也需要根据字段名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