2016-04-25 57 views
0

我有一堆實體在字段名稱前使用下劃線前綴,否則使用camelcase。如何自定義spring-data Repository方法名稱?

@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 

現在我移植這個項目去春來數據,我得到許多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的命名策略,但是如何更改查詢方法生成命名算法以在實體上或以JPQL術語映射「findByFoo」 - >「_foo」其中x._foo__id =? 1「

我使用的是老式的xml配置,沒有彈簧啓動。


編輯:發現這個in the docs,這是沒有幫助的..

「當我們把強調作爲保留字符,我們強烈建議,以 遵循標準的Java命名約定(即不使用下劃線 屬性名稱,而不是駱駝案例)。「

也許我應該重構字段名稱,刪除下劃線,然後實現一個hibernate命名策略,將下劃線添加回來?

+0

沒有稱爲「foo」的屬性。它在它之前有一個下劃線,而你的Spring方法沒有這個... –

+0

沒錯。因此,這個問題。我想知道如何在實體上映射「findByFoo」 - >「_foo」。 – Casey

+0

如果僅因爲列名具有下劃線而具有下劃線,則可以將其從Java字段中刪除,並使用@Column註釋指定自定義列名稱。 – dunni

回答

1

我可以重複文檔中的內容(儘管我對「無用」部分感興趣)。爲您的Java代碼使用標準的Java約定。使用商店特定的方法來定製屬性映射到數據庫表的方式。 JPA爲此提供了@Column註釋。

+1

是的,謝謝你的建議。我最終重構了我的字段名稱並使用命名策略來避免添加列註釋。感謝您的春季資料:) – Casey