如何自定义 spring-data Repository 方法名?

How to customize the spring-data Repository method names?

我有一堆实体在字段名称前使用下划线前缀,否则使用驼峰命名法。

@Entity
public class Customer {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long _id;


  private String _firstName;
  private String _lastName;

  @OneToOne
  private Foo _foo;

  // … methods omitted
}

存储库

public interface CustomerRepository extends PagingAndSortingRepository<Customer, Long> {

    Iterable<Customer> findByFoo(Foo foo);
}

表格中相应的字段也使用此命名方案:

Customer: _id, _firstName, _lastName, _foo__id

现在我正在将此项目迁移到 spring-data,我收到许多 IllegalArgumentExceptions :

Could not create query metamodel for method
public abstract java.lang.Iterable  

com.example.repository.CustomerRepository.findByFoo(com.example.model.Foo)!

 Unable to locate Attribute  with the given name [foo] on this ManagedType [com.example.model.Customer]

我不需要更改 hibernate 的命名策略,但我如何更改查询方法生成命名算法 以映射 "findByFoo" -> "_foo" on the实体,或者用 JPQL 术语 "where x._foo__id = ?1"

我使用的是老式 xml 配置,没有 spring 引导。


编辑:找到这个 in the docs,没有帮助..

"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)."

也许我应该重构字段名称,删除下划线,然后实施一个将下划线添加回来的休眠命名策略?

我可以重复文档中的内容(尽管我对 "isn't helpful" 部分感兴趣)。为您的 Java 代码使用标准 Java 约定。使用特定于商店的方法来自定义将属性映射到数据库表的方式。 JPA 为此提供了 @Column 注释。