Sprint @Query注解的用法(nativeQuery=true/false)(Spring Data JPA)ITeye - 众发娱乐

Sprint @Query注解的用法(nativeQuery=true/false)(Spring Data JPA)ITeye

2019-01-10 15:14:31 | 作者: 怀寒 | 标签: 运用,注解,一个 | 浏览: 2695

1. 一个运用@Query注解的简略比如
@Query(value = "select name,author,price from Book b where b.price ?1 and b.price ?2")
List Book findByPriceRange(long price1, long price2);


2.Like表达式
@Query(value = "select name,author,price from Book b where b.name like %:name%")
List Book findByNameMatch(@Param("name") String name);


3. 运用Native SQL Query(nativeQuery=true则运用原生SQL默许HQL)
所谓本地查询,便是运用原生的sql句子(依据数据库的不同,在sql的语法或结构方面或许有所区别)进行查询数据库的操作。
@Query(value = "select * from book b where b.name=?1", nativeQuery = true)
List Book findByName(String name);


4. 运用@Param注解注入参数
@Query(value = "select name,author,price from Book b where b.name = :name AND b.author=:author AND b.price=:price")
List Book findByNamedParam(@Param("name") String name, @Param("author") String author,
 @Param("price") long price);


5. SPEL表达式(运用时请参阅最终的弥补阐明)
#{#entityName}值为Book目标对应的数据表称号(book)。
public interface BookQueryRepositoryExample extends Repository Book, Long {
 @Query(value = "select * from #{#entityName} b where b.name=?1", nativeQuery = true)
 List Book findByName(String name);
}


6. 一个较完好的比如
public interface BookQueryRepositoryExample extends Repository Book, Long {
 @Query(value = "select * from Book b where b.name=?1", nativeQuery = true) 
 List Book findByName(String name);// 此办法sql将会报错(java.lang.IllegalArgumentException),看出原因了吗,若没看出来,请看下一个比如
 @Query(value = "select name,author,price from Book b where b.price ?1 and b.price ?2")
 List Book findByPriceRange(long price1, long price2);
 @Query(value = "select name,author,price from Book b where b.name like %:name%")
 List Book findByNameMatch(@Param("name") String name);
 @Query(value = "select name,author,price from Book b where b.name = :name AND b.author=:author AND b.price=:price")
 List Book findByNamedParam(@Param("name") String name, @Param("author") String author,
 @Param("price") long price);
}



版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表众发娱乐立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章