注解@Query
来源:互联网 发布:龙虎榜数据哪里可以看 编辑:程序博客网 时间:2024/06/15 14:13
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
所谓本地查询,就是使用原生的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);}
7. 解释例6中错误的原因:
因为指定了nativeQuery = true,即使用原生的sql语句查询。使用java对象'Book'作为表名来查自然是不对的。只需将Book替换为表名book。
@Query(value = "select * from book b where b.name=?1", nativeQuery = true)List<Book> findByName(String name);
阅读全文
0 0
- 注解@Query
- Retrofit之Query注解
- SpringData系列@Query注解及@Modifying注解
- Spring Data JPA 常用注解 @Query、@NamedQuery
- Spring data jpa 之 Query注解
- @Query注解的用法(Spring Data JPA)
- SpringData-3 @Query与@Modifying注解
- @Query注解的用法(Spring Data JPA)
- @Query注解的用法(Spring Data JPA)
- Spring Data JPA进阶-@Query注解
- @Query注解的用法(Spring Data JPA)
- @Query注解的用法(Spring Data JPA)
- 在JPA的@Query注解中使用limit条件
- spring data jpa @Query注解中delete语句报错
- 使用JPA中@Query 注解实现update 操作
- Spring Data JPA 使用@Query注解执行原始Sql
- SpringData JPA @query注解使用原生代码报错问题
- 【Android】Retrofit网络请求参数注解,@Path、@Query、@QueryMap...
- Spring 报错 : org.springframework.beans.factory.BeanDefinitionStoreException
- 微信运动刷步数软件,真正一键搞定2017
- Linux下分卷压缩较大的文件
- POJ 1157 LITTLE SHOP OF FLOWERS
- 求图中最长路径
- 注解@Query
- 八大排序算法_直接插入排序(Straight Insertion Sort)
- Dijkstra算法
- Android ORMLite框架组合查询条件
- 多校连萌 (4)GJJ来签到
- 常用的运行命令
- 【POJ3177】Redundant Paths-边双连通分量+缩点
- img图片标记
- 多校连萌(4)GJJ的日常之暴富梦