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

时间:2016-04-25 17:38:11

标签: java spring jpa spring-data-jpa

我有很多实体在字段名称之前使用下划线前缀,否则使用camelcase。

@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的命名策略,但是如何更改查询方法生成命名算法以映射&#34; findByFoo&#34; - &GT; &#34; _foo&#34;在实体上,或用JPQL术语&#34;其中x._foo__id =?1&#34;

我使用的是旧式xml配置,没有弹簧启动。

修改:找到此in the docs,这对您没有帮助..

  

&#34;当我们将下划线视为保留字符时,我们强烈建议   遵循标准的Java命名约定(即不使用下划线)   属性名称,但改为驼峰案例。&#34;

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

1 个答案:

答案 0 :(得分:1)

我可以重复一下文档中的内容(虽然我对“无用”部分感兴趣)。为Java代码使用标准Java约定。使用特定于商店的方法来自定义属性映射到数据库表的方式。 JPA为此提供了@Column注释。

相关问题