|  | 本文参考《精通Spring:JavaWeb开发技术详解》,作者:孙卫琴,清华大学出版社出版 
 如果用@Query注解来设定查询条件,方法名字不需要符合特定的规则。例如以下CustomerDao接口通过@Query注解标识了两个查询方法:
 | …… import org.springframework.data.jpa.repository.Query;
 
 @Repository
 public interface CustomerDao extendsJpaRepository<Customer,Long>{
 @Query("from Customer where name = ?1")
 List<Customer> queryByName(String name);
 
 @Query("from Customer where name like?1  and age>= ?2")
 List<Customer> queryByNameAge(String name,int age);
 }
 | 
 以下程序代码调用上述查询方法:
 
 
 | List<Customer>result1=customerDao.queryByName("Tom"); 
 List<Customer>result2=customerDao.queryByNameAge("Tom",18);
 | 
 运行以上程序代码时,底层的Hibernate依次执行以下SQL查询语句:
 
 
 | select * from CUSTOMERS where NAME="Tom"; select * from CUSTOMERS where NAME like "Tom"and AGE>=18;
 | 
 默认情况下,向@Query注解提供的是面向对象的JPQL(JPA Query Language)查询语句。JPQL查询语句中引用的是类以及类的属性,例如:
 
 
 | @Query("from Customer where name like?1  and age>= ?2") | 
 以上JPQL查询语句中引用了Customer类名以及name和age属性名。
 
 此外,把@Query注解的nativeQuery属性设为true,就可以向Query注解直接提供SQL查询语句。nativeQuery属性的默认值为false。
 例如以下CustomerDao接口中的@Query注解采用了SQL查询语句:
 
 
 | @Repository public interface CustomerDao  extends JpaRepository<Customer,Long>{
 
 @Query(value="select * from CUSTOMERSwhere NAME = ?1 ",
 nativeQuery=true)
 List<Customer> queryByNameNative(String name);
 
 @Query(
 value="select * from CUSTOMERS whereNAME like ?1 and AGE>=?2",
 nativeQuery=true)
 List<Customer> queryByNameAgeNative(String name,int age);
 }
 | 
 以上SQL查询语句引用的是数据库中的表和字段的名字,而不是类名以及类的属性名,这是和JPQL查询语句的显著区别。
 
 
 
 
 程序猿的技术大观园:www.javathinker.net
 |  |