Use the @Query annotation to implement queries

Use the @Query annotation to implement queries



//  -- ---------------------------------- Annotated with @Query 
// Query without parameters
 @Query (" select p from Person p where p.id = ( select  max (p2.id) from Person p2)")
Person getMaxIdPerson();

/**
 * Parameter name and parameter order coupling
 * @param lastName
 * @param email
 * @return
 */
@Query("select p from Person p where lastName=?1 and email=?2")
Person readPersonByLastNameAndEmail(String lastName,String email);

@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 annotation supports percent sign
 @Query (" select p from Person p where lastName like  % ? 1 % ")
Person readPersonByLike2(String likeName);

//  @Query annotation supports percent sign
 @Query (" select p from Person p where lastName like  % :lastName % ")
Person readPersonByLike3(@Param("lastName")String name);

// 使用原生的 SQL
@Query(value="select * from jpa_person p1 where p1.last_name like %:lastName%",nativeQuery=true)
Person getPersonUsingOriginSQL(@Param("lastName")String lastName);
Test code:

// The following test @Query annotation
 @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);
}
Note: If we use native SQL, the statement printed on the console will also be native SQL, such as the console print of our last test method above:

write picture description here

Read the full article

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324505773&siteId=291194637