Sprint @Query注解的用法(nativeQuery=true/false)(Spring Data JPA)
[color=red][b]1. 一个使用@Query注解的简单例子[/b][/color] [code="java"]@Query(value = "select name,author,price from Book b where b.price>?1 and b.price findByPriceRange(long price1, long price2);[/code] [b]2.Like表达式[/b] [code="java"]@Query(value = "select name,author,price from Book b where b.name like %:name%") List findByNameMatch(@Param("name") String name);[/code] [size=medium][color=blue][b]3. 使用Native SQL Query(nativeQuery=true则使用原生SQL默认HQL)[/b][/color][/size] 所谓本地查询,就是使用原生的sql语句(根据数据库的不同,在sql的语法或结构方面可能有所区别)进行查询数据库的操作。 [code="java"]@Query(value = "select * from book b where b.name=?1", nativeQuery = true) List findByName(String name);[/code] [color=red][b]4. 使用@Param注解注入参数[/b][/color] [code="java"]@Query(value = "select name,author,price from Book b where b.name = :name AND b.author=:author AND b.price=:price") List findByNamedParam(@Param("name") String name, @Param("author") String author, @Param("price") long price);[/code] [b]5. SPEL表达式(使用时请参考最后的补充说明)[/b] '#{#entityName}'值为'Book'对象对应的数据表名称(book)。 [code="java"]public interface BookQueryRepositoryExample extends Repository{ @Query(value = "select * from #{#entityName} b where b.name=?1", nativeQuery = true) List findByName(String name); }[/code] [b]6. 一个较完整的例子[/b] [code="java"] public interface BookQueryRepositoryExample extends Repository { @Query(value = "select * from Book b where b.name=?1", nativeQuery = true) List findByName(String name);// 此方法sql将会报错(java.lang.IllegalArgumentException),看出原因了吗,若没看出来,请看下一个例子 @Query(value = "select name,author,price from Book b where b.price>?1 and b.price findByPriceRange(long price1, long price2); @Query(value = "select name,author,price from Book b where b.name like %:name%") List 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 findByNamedParam(@Param("name") String name, @Param("author") String author, @Param("price") long price); }[/code]