zoukankan      html  css  js  c++  java
  • 使用 @Query 注解实现查询

    // ------------------------------------ 使用 @Query 注解
    // 没有参数的查询
    @Query("select p from Person p where p.id = (select max(p2.id) from Person 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, long price2); /** * 参数绑定 @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 public void testQueryAnnotationWithoutParam(){ Person person = personRepository.getMaxIdPerson(); System.out.println(person); } @Test public void testQueryAnnotationWithParam(){ Person person = personRepository.readPersonByLastNameAndEmail("liwei","liwei@sina.com"); System.out.println(person); } @Test public void testQueryAnnotationWithParamThroughName(){ Person person = personRepository.readPersonByLastNameAndEmailThroughName("zhouguang","zhouguang@163.com"); System.out.println(person); } @Test public void testQueryAnnotationWithParamThroughLike(){ Person person = personRepository.readPersonByLike("%zhou%"); System.out.println(person); } @Test public void testQueryAnnotationWithParamThroughLike2(){ Person person = personRepository.readPersonByLike2("hu"); System.out.println(person); } @Test public void testQueryAnnotationWithParamThroughLike3(){ Person person = personRepository.readPersonByLike3("wei"); System.out.println(person); } @Test public void testQueryAnnotationWithParamThroughLike4(){ Person person = personRepository.getPersonUsingOriginSQL("wei"); System.out.println(person); }
  • 相关阅读:
    学习 Linux 几点忠告【转载】
    游侠更新仙剑全系列免CD补丁(支持WIN7 SP1)【转载】
    更改数据库对象所有者
    数据库 行列相互转化
    JQuery计时器
    js操作cookies
    利用自定义DataTable来重画数据集的用法
    asp.net mvc 从客户端中检测到有潜在危险的 Request.Form 值的解决方法
    CS144 Lab
    CS231n Assignment #2
  • 原文地址:https://www.cnblogs.com/xiaolei2017/p/8863660.html
Copyright © 2011-2022 走看看