简体   繁体   中英

How to map class attributes with underscores “_” in their names in Spring-data JPA

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
}       

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM