// ------------------------------------ 使用 @Query 注解 //没有参数的查询 @Query("select p from Person p where p.id = (select max(p2.id) fromPerson p2)") Person getMaxIdPerson(); /** * 参数名称和参数顺序耦合 * @param lastName * @param email * @return */ @Query("select p from Person p where lastName=?1 and email=?2") Person readPersonByLastNameAndEmail(String lastName,String email);
@Query(value = "select name,author,price from Book b where b.price>?1 and b.price<?2") List<Book> findByPriceRange(long price1, longprice2); /** * 参数绑定 @Param注解注入参数 */ @Query("select p from Person p where email=:email and lastName=:name") Person readPersonByLastNameAndEmailThroughName(@Param("name") String lastName,@Param("email") String email);// 使用 like @Query("select p from Person p where lastName like ?1") Person readPersonByLike(String likeName); // @Query注解支持使用百分号 @Query("select p from Person p where lastName like %?1%") Person readPersonByLike2(String likeName); // @Query注解支持使用百分号 @Query("select p from Person p where lastName like %:lastName%") Person readPersonByLike3(@Param("lastName")String name); // 使用原生的 SQL 加上 nativeQuery=true @Query(value="select * from jpa_person p1 where p1.last_name like %:lastName%",nativeQuery=true) Person getPersonUsingOriginSQL(@Param("lastName")String lastName); 测试代码: // 以下测试 @Query注解 @Test publicvoid testQueryAnnotationWithoutParam(){ Person person =personRepository.getMaxIdPerson(); System.out.println(person); } @Test publicvoid testQueryAnnotationWithParam(){ Person person = personRepository.readPersonByLastNameAndEmail("liwei","liwei@sina.com"); System.out.println(person); } @Test publicvoid testQueryAnnotationWithParamThroughName(){ Person person = personRepository.readPersonByLastNameAndEmailThroughName("zhouguang","zhouguang@163.com"); System.out.println(person); } @Test publicvoid testQueryAnnotationWithParamThroughLike(){ Person person = personRepository.readPersonByLike("%zhou%"); System.out.println(person); } @Test publicvoid testQueryAnnotationWithParamThroughLike2(){ Person person =personRepository.readPersonByLike2("hu"); System.out.println(person); } @Test publicvoid testQueryAnnotationWithParamThroughLike3(){ Person person =personRepository.readPersonByLike3("wei"); System.out.println(person); } @Test publicvoid testQueryAnnotationWithParamThroughLike4(){ Person person =personRepository.getPersonUsingOriginSQL("wei"); System.out.println(person); }
使用 @Query 注解实现查询
免责声明:文章转载自《使用 @Query 注解实现查询》仅用于学习参考。如对内容有疑问,请及时联系本站处理。
上篇POI操作word和html相互转化前端传多个数组集合,后端接收并匹配下篇
宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=