Total Pageviews

2016/01/07

[Spring Framework] Spring Data JPA @Query

If I have an SQL query statement which is simple, and not dynamic, we can utilize @Query to fulfill out requirement.

Example 1. Apply @Query without parameter:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public interface Dbm002fbRepository extends EntityRepository<Dbm002fb, String> {

    /**
     * 找出 kind_code = 'DEBTT' 的下拉單.
     * 
     * @return the list
     */
    @Query(value = "select * from dbm002fb where kind_code='DEBTT' and is_use='Y' order by code_no", nativeQuery = true)
    List<Dbm002fb> findDEBTT();

    /**
     * 找出 kind_code = 'DEBTI' 的下拉單.
     * 
     * @return the list
     */
    @Query(value = "select * from dbm002fb where kind_code='DEBTI' and is_use='Y' order by code_no", nativeQuery = true)
    List<Dbm002fb> findDEBTI();
}


Example 2. Apply @Query and bind named parameters:
1
2
3
4
5
6
7
public interface Fms426faRepository extends EntityRepository<Fms426fa, Fms426faId>,
        Fms426faRepositoryCustom {

    @Query(value = "select * from fms426fa where accyr=:twYear and data_type='T' order by rpt_no", nativeQuery = true)
    List<Fms426fa> findTAlcAmt(@Param("twYear") String twYear);

}


Reference
[1] http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query
[2] http://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-creating-database-queries-from-method-names/

No comments: