【问题标题】:Spring Data REST - How to sort an entity by JSON ignored field?Spring Data REST - 如何通过 JSON 忽略字段对实体进行排序?
【发布时间】:2018-02-18 16:37:24
【问题描述】:

我正在使用 Spring Data REST,我的项目中有以下实体。

@Data
@Entity
public class Loan{

    @Id
    @GeneratedValue
    private Long id;

    @JsonIgnore
    private Long createdDate;

    private Long amount;

    private Long repaymentStartDate;

}

现在我想按createdDate 对贷款进行排序,该createdDate 将自动填充并使用JSONIgnored 以防止更新。但是当我调用端点loans?sort=createdDate 时,我无法按createdDate 对贷款进行排序。

我该如何解决这个问题?

这是我的存储库:

public interface LoanRepository extends PagingAndSortingRepository<Loan, Long>{

}

【问题讨论】:

  • restcontroller 长什么样子?请将代码添加到您的问题中。
  • 由于我使用的是 Spring Data REST,因此无需编写单独的控制器。当我扩展存储库接口时,Spring 会生成它。
  • 当该字段使用“@JsonIgnore”注释时,该字段对用户不可见。所以很明显,不可能按照用户看不到的东西对结果进行排序。

标签: java spring spring-boot spring-data-rest


【解决方案1】:

要解决此问题,请尝试将 @JsonIgnore 替换为 @JsonProperty(access = READ_ONLY)。它可以防止 createdDate 发生变化,但仍保留在 json 正文中。

更新

对于 Spring Boot 1.5.10+ 而不是 @JsonProperty(access = READ_ONLY),您可以在实体顶部使用 @JsonIgnoreProperties("createdDate")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2015-10-15
    • 2019-02-09
    • 2017-06-03
    • 2023-02-10
    • 2016-07-01
    • 1970-01-01
    相关资源
    最近更新 更多