Spring Data REST:如何按JSON忽略字段createdDate对实体排序?
这个问题的核心原因是:@JsonIgnore注解会同时告诉Jackson和Spring Data REST完全忽略这个字段——不仅禁止客户端更新它,还会让Spring Data REST把该字段排除在可排序、可查询的属性列表之外。要满足「自动填充、禁止更新、允许排序」这三个需求,我们可以用以下几种方案:
方案一:用@JsonProperty(access = READ_ONLY)替代@JsonIgnore
如果你的需求只是禁止客户端更新该字段,但允许响应中返回它,这个方案最简单。@JsonProperty(access = JsonProperty.Access.READ_ONLY)会让Jackson在反序列化(接收客户端请求)时忽略该字段(防止更新),但序列化(返回响应)和Spring Data REST的排序/查询逻辑都会识别这个字段。
示例代码:
import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.data.annotation.CreatedDate; import javax.persistence.EntityListeners; import java.time.LocalDateTime; @Entity @EntityListeners(AuditingEntityListener.class) public class Loan { // 其他字段... @CreatedDate @JsonProperty(access = JsonProperty.Access.READ_ONLY) private LocalDateTime createdDate; // getter/setter... }
这样修改后,你调用loans?sort=createdDate就能正常排序,同时客户端无法通过PUT/PATCH请求修改createdDate。
方案二:保留@JsonIgnore,手动配置Spring Data REST允许该字段排序
如果你不想在响应中返回createdDate(也就是保留@JsonIgnore),那需要手动告诉Spring Data REST:这个字段虽然不暴露给客户端,但支持排序。
你可以创建一个Spring配置类,实现RepositoryRestConfigurer接口,手动注册createdDate为可排序字段:
import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer; import com.yourpackage.Loan; @Configuration public class RestRepositoryConfig implements RepositoryRestConfigurer { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { // 针对Loan实体,添加createdDate到可排序字段列表 config.getMetadataConfiguration() .forDomainType(Loan.class) .addSortableField("createdDate"); } }
这个配置会让Spring Data REST忽略Jackson的@JsonIgnore限制,允许对createdDate字段进行排序,同时该字段依然不会出现在响应体中,也无法被客户端更新。
方案三:确保Spring Data Auditing配置生效
既然你的createdDate是自动填充的,应该已经用到了Spring Data的审计功能(@CreatedDate + @EntityListeners(AuditingEntityListener.class))。别忘了在主启动类上添加@EnableJpaAuditing注解,保证自动填充逻辑正常运行:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; @SpringBootApplication @EnableJpaAuditing public class LoanApplication { public static void main(String[] args) { SpringApplication.run(LoanApplication.class, args); } }
这是基础配置步骤,配合上面任意一个方案,就能完美实现你的需求。
内容的提问来源于stack exchange,提问作者Charlie

