【问题标题】:How to sort by json field in Spring data jpa?如何在 Spring data jpa 中按 json 字段排序?
【发布时间】:2019-11-01 10:21:07
【问题描述】:

我正在使用spring data jpa规范查询做动态查询

我有一个问题是我需要按 json 字段排序并且 我在谷歌搜索了很多,但仍然不知道该怎么做

用sql很容易做到:

select * , JSON_EXTRACT(json_column, '$.age') as age from table order by  age desc ;

有什么想法吗?谢谢大家。

【问题讨论】:

    标签: hibernate jpa spring-data-jpa criteria-api


    【解决方案1】:

    我刚刚找到了另一种方法。 这是解决方案:

    @Entity
    @Data
    @EntityListeners(AuditingEntityListener.class)
    public class Expert extends BaseEntity {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
    
        @Column(unique = true)
        private String code;
    
        @Formula(value = "JSON_EXTRACT(expert_information, '$.basicInformation.nameEN')")
        private String age;
    
        @Type(type = "json")
        @Column(columnDefinition = "json", nullable = false)
        private Map<String, Object> expertInformation;
    }
    

    这个解决方案的关键是使用@Formula 注释。在该注释中,使用 json 函数将其提取为普通属性。

    【讨论】:

      【解决方案2】:

      您需要将age 设为正常的持久属性。

      您可以通过创建一个包含 id 和 age 列的 2 列数据库视图来实现这一点,其中 age 列基于 JSON_EXTRACT,如您的问题所示。

      然后您可以在您的实体上使用@SecondaryTable,以便它可以映射到其表和您刚刚创建的视图,并在 id 列上连接。

      然后,您可以将年龄设为永久属性。然后,您可以按年龄对过滤器进行排序,就像对任何其他持久性属性一样。

      @Entity
      @Table("...")
      @SecondaryTable("my_new_view")
      public class MyEntity{
      
          //existing mappings
      
          @Column(name ="age" table="my_new_view", insertable="false", updateable="false")
          private Integer age; //ensure to use wrapper type here to avoid issues
      }
      

      【讨论】:

      • 感谢您的回复。但我找到了另一种方法。
      猜你喜欢
      • 2018-01-02
      • 1970-01-01
      • 2021-10-18
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 2017-01-19
      相关资源
      最近更新 更多