Spring Data JPA的@Query注解基本用法

@Query 注解是 JPA 中的一个注解,使用的比较频繁。在Dao层接口继承统一的Repository接口。
在@Query 注解中,如果用到 的形式获取参数。(后面数字表示第几个参数。)那么它是按照方法的参数顺序来取值的,必须与方法中的参数顺序一致

@Query("select u from User u where u.id>?1 and u.username=?2")
List<User> getUserByParam(Long id ,String username);

参数名称绑定用@Param("email"),SQL中用 :email ,email为传入参数

@Query(value = "from User u where u.username=:name and u.email=:email")
User findByNameAndEmail(@Param("name")String name, @Param("email")String email);

传一个对象 :name 对应 @Param中的 name,:age 对应 @Param中的 age,:#{#user.name} : 对象中的参数使用方法

@Query(value = "select  u from User u  where u.username = :#{#user.username} and u.age = :#{#user.age}")
List<User> queryObjectParamByNameAndAge(@Param("user") User user);
  1. 以下是本地查询,其实就是正常我们写的Sql语句,nativeQuery = true.默认为false
@Query(value="select * from user u, town t where u.id = t.id and t.place = ?1", nativeQuery = true)
User UsergetUserByPlace(String place);
  1. 当方法需要修改数据时,加上@Modifying,当然也要加上事务控制@Transactional,不然会报错
@Modifying
@Query("update User set username=?1 where id=?2")
 void updateUsernameById(String username,Long id);

模糊查询

@Query(value = "from User u where u.username like %:username%")
List<User> findByNameLike(@Param("username")String username);

展示传入集合参数查询,或者用List<>

@Query(value = "from User u where u.username in :nameList")
List<User> findByNameIn(@Param("nameList")Collection<String> nameList);

展示使用Spring自带分页查询

@Query("from User u")
Page<User> findAllPage(Pageable pageable);

展示带有条件的分页查询

@Query(value = "from User u where u.email like %:emailLike%")
Page<User> findByEmailLike(Pageable pageable, @Param("emailLike")String emailLike);
  1. Sort 排序根据姓名模糊查询排序
@Query("select u from User u where u.username like ?1%")
List<User> findByAndSort(String name, Sort sort);

删除

@Transactional
@Modifying
@Query("delete from Useru where u.id in (?1)")
 public void deleteByInIds(List<Integer> ids);

新增的话直接调用save()方法


版权声明:本文为qq_42289636原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。