Spring Data JPA @Query注解介绍

一、查询

1、用?的形式获取参数

示例:

@Query("select u from Customer u where emailAddress = ?1 and name = ?2")
User findByEmailAndName(String emailAddress, String name);

在这里?+数字代表占位符,比较特殊的是数字从1开始,而非从0开始。?1代表顺序中的第一个参数。

2、使用命名参数绑定查询名称的方法

示例:

@Query("select u from Customer u where u.firstname = :firstname or u.lastname = :lastname")
User findByLastnameOrFirstname(@Param("lastname") String lname, @Param("firstname") String fname);

用=:加上变量名的方式来绑定参数,这里是与方法参数中有@Param的值匹配的,而不是与实际参数匹配的,且@Param的顺序可以随意放置。

二、利用@Query进行修改

当使用@Query时,如果想要修改,需要加入@Modifying进行修饰,相当于 @Update 注解。

@Modifying
@Query("update Customer u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);

三、注意事项

在JPQL的语法中,表名的位置对应Entity的名称,字段对应Entity的属性,如果想要使用原生SQL(即表名位置和字段位置应该要分别对应表名和表字段名)需要在@Query注解中设置nativeQuery=true。 示例:

@Modifying
@Query(value = "update customer u set u.firstname = ?1 where u.lastname = ?2", nativeQuery = true)
int setFixedFirstnameFor(String firstname, String lastname);
经验分享 程序员 微信小程序 职场和发展