【问题标题】:Spring JpaRepository find entities from attribute using unconventional namingSpring JpaRepository 使用非常规命名从属性中查找实体
【发布时间】:2019-07-02 18:29:26
【问题描述】:

以前在Spring 1.5.10.RELEASE下可以用,在Spring 2.0.7.RELEASE下不行,不知道为什么:

实体

@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.RELEASE 下遇到的错误是

java.lang.IllegalArgumentException:无法在此 ManagedType 上找到具有给定名称 [CLocationId] 的属性。

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

  • findBycLocationId - 找不到类型 Location 的属性 orderBycLocationIdAsc!
  • findByClocationId - 找不到类型 Location 的属性 clocationId!您的意思是“CLocationId”、“cLocationId”吗?
  • findByCLocationId - 无法在此 ManagedType 上找到具有给定名称 [CLocationId] 的属性

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

【问题讨论】:

  • 当 getter 和属性名称不匹配时,我有时会遇到一些问题。但我认为这更像是一个 IDE 问题(它只下划线但可以编译)。很好检查。
  • 不是IDE问题。 Maven 不会编译...

标签: java spring spring-data-jpa


【解决方案1】:

你可以像这样使用方法名:

Location findByC_Location_Id(String cLocationId);

this 可以提供参考资料

【讨论】:

    【解决方案2】:

    你可以在你的方法official documentation中使用@Query注解。

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

    【讨论】:

    • 很好的解决方法,但我必须这样做吗?为什么这在以前的 Spring 版本中有效,而不是现在?这种类型的属性命名真的是 Spring 不再支持的非常规吗?
    • @ØysteinAmundsen 老实说,我不知道。我看到了这个docs.spring.io/spring-data/jpa/docs/current/reference/html/…,但我不知道。
    猜你喜欢
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 2015-09-04
    相关资源
    最近更新 更多