zhe*_* ma 5 hibernate jpa criteria-api spring-data-jpa
我正在使用spring data jpa规范查询来做动态查询
我有一个问题,我需要按 json 字段排序,我在 google 上搜索了很多,但仍然不知道该怎么做
很容易通过sql来完成:
select * , JSON_EXTRACT(json_column, '$.age') as age from table order by age desc ;
Run Code Online (Sandbox Code Playgroud)
有任何想法吗 ?谢谢大家。
我刚刚找到了另一种方法来做到这一点。这是解决方案:
@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;
}
Run Code Online (Sandbox Code Playgroud)
该解决方案的关键是使用@Formula注释。在该注释中,使用 json 函数将其提取为普通属性。
您需要创建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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2985 次 |
| 最近记录: |