How to map class attributes to underscores "_" in their names in Spring-data JPA

Does JPA with Spring-Data have problems with underscore "_" attributes in their names? This is my interface that extends JpaRepository


public interface I_My_Class extends JpaRepository<MyClass, Long> {

    public MyClass findByA_my_table_id (Long headerId);


This line: findByA_my_table_id (Long headerId);

gives this error:

Invalid derived query! No property "a" found for type MyClass!

If I call the method public MyClass findBya_my_table_id (Long headerId);

, it gives me the same error. If I call the attribute amytableid

without underscore, I don't get the error, but if I do, it is not easy to read later. This is the class where I have a table attribute:

public class MyClass implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column (name="MY_TABLE_ID", nullable=false)
    private Long a_my_table_id; // <-- this is the attribute that I try to put in the named query



source to share

1 answer

Yes Spring Data will have problems with underscores in Entity attribute names. The reason why JpaRepository just expects attributes with proper Java Standard naming conventions, for example, property names must be in lower case. (if you can add multiple nouns to make them more meaningful, then it is better to make the first letter of the nouns uppercase than the first)

String aMyTableId;


The above properties will create a JpaRepository command to create a method like

List<MyClass> findByAMyTableId(String aMyTableId);


This will not give a compilation error.

If you want to write custom queries, you can use the @Query API. You can write an object oriented query here.

@Query("Select myclass from MyClass myclass where myclass.aMyTableId=?1 and myclass.activeFlag='1'")
List<MyClass> findByAMyTableIdWithActiveFlagOn(String aMyTableId);


You can find many tutorials and sites explaining how to write custom queries.



All Articles