代码之家  ›  专栏  ›  技术社区  ›  Øystein Amundsen

Spring JpaRepository使用非常规命名从属性中查找实体

  •  4
  • Øystein Amundsen  · 技术社区  · 7 年前

    以下内容曾在Spring 1.5.10中使用。发布,但在Spring 2.0.7中不起作用。释放,我不知道为什么:

    实体

    @Entity
    @Table(name = "locations")
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    public class Location {
      // ... unimportant stuff
      @Column(name = "c_locations_id")
      private String cLocationId;
      // ... more unimportant stuff
    }
    

    存储库 (又名“问题”)

    @Repository
    public interface LocationRepository extends JpaRepository<Location, Long>, JpaSpecificationExecutor<Location> {
      Location findByCLocationId(String cLocationId);
      List<Location> findAllByOrderByCLocationIdAsc();
    }
    

    我在Spring 2.0.7下遇到的错误。以上代码的发布版本是

    JAVAlang.IllegalArgumentException:无法在此ManagedType上找到名为[CLocationId]的属性。

    由于其他情况,我无法更改属性的名称,因此我尝试了存储库中不同的方法:

    • findBycLocationId -找不到类型位置的属性OrderByClocationIdsc!
    • findByClocationId -找不到类型位置的属性clocationId!你是说“CLocationId”吗?
    • findByCLocationId -在此ManagedType上找不到名为[CLocationId]的属性

    它想要什么?!我只是想升级框架。。。😭

    2 回复  |  直到 7 年前
        1
  •  5
  •   Hakob Hakobyan    7 年前

    可以使用如下方法名:

    Location findByC_Location_Id(String cLocationId);

    this 可以提供参考

        2
  •  2
  •   David Pérez Cabrera    7 年前

    你可以用 @Query 方法中的注释 official documentation .

    @Query("select l from Location l where l.cLocationId = ?1")
    Location findByCLocationId(String cLocationId);
    
    @Query("select l from Location l")
    List<Location> findAllByOrderByCLocationIdAsc();