SpringJPA的Sort如何对带有下划线的字段排序?

各位前辈,第一次用SpringJPA。现在实体类有一个字段是这样的:

    private String movie_id;

而我想通过这个字段排序,继承PagingAndSortingRepository后,代码为:

    Sort sort = new Sort(Sort.Direction.DESC,"movie_id");
    Pageable pageable = PageRequest.of(0,PAGE_LIMIT,sort);
    Page<MovieInfo> movieInfopage = movieInfoRepository.findAll(pageable);
    

可是报错了:

org.springframework.data.mapping.PropertyReferenceException: No property movie found for type MovieInfo!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:92) ~[spring-data-commons-2.0.6.RELEASE.jar:2.0.6.RELEASE]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:356) ~[spring-data-commons-2.0.6.RELEASE.jar:2.0.6.RELEASE]

手动改movie_id为movieId后即可操作。
那肯定是框架无法识别下划线 ....
前辈们咋办!可以不用大改字段名么?

阅读 5.2k
2 个回答

通过实验发现了,bean中的字段可以定义为驼峰,通过hibernate的命名策略可以自动把驼峰转化为下划线,然后Sort中需要的其实是bean中的字段。例如定义为movieId,数据会自动转为movie_id,然后会根据bean的字段也就是movieId去排序。

首先,java field应该用camel case,一开始就不应该用下划线。再说你这个问题,根据spring文档,下划线是保留字段:“As we treat underscore as a reserved character we strongly advise to follow standard Java naming conventions (i.e. not using underscores in property names but camel case instead).”两个解决方案:
1.movie_id改成movieId

  1. 试试两个下划线escape掉下划线,Sort sort = new Sort(Sort.Direction.DESC,"movie__id");
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题