3

Does JPA with Spring-Data have a problem with attributes with underscores "_" 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 name the method public MyClass findBya_my_table_id (Long headerId); it gives me the same error. If I name the attribute amytableid without the underscores I don't get the error but if I do that it's not easy to read later on. This is the class where I have the table attribute:

@Entity
@Table(name="MyTable")
public class MyClass implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @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
}       
Servy
  • 202,030
  • 26
  • 332
  • 449
stackUser2000
  • 1,615
  • 11
  • 32
  • 55
  • 3
    You'll always have problems if you don't respect standard conventions, especially with frameworks like Spring Data which heavily rely on these standard conventions. Do the right thing, and simply respect the standard naming conventions. You'll have fewer problems, and your code will be more readable. Variables don't contain underscores. Period. – JB Nizet Sep 15 '14 at 21:18

1 Answers1

3

Yes Spring Data will have problem with underscores in Entity attribute names. Reason being JpaRepository simply expects attributes with proper Java Standard naming conventions eg property names should be in lower case. (if you can add multiple nouns to make it more meaning full then better make first letter of nouns in upper case except the first one)

String aMyTableId;

Above property would create tell JpaRepository to create a method like

List<MyClass> findByAMyTableId(String aMyTableId);

This would not give compilation error.

In case you want to write custom queries then you can use @Query API. Here you can write Object oriented query.

@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.

Suvasis
  • 1,451
  • 4
  • 24
  • 42