springData学习(二)@Query注解详解

    xiaoxiao2022-07-14  162

    在上一篇中我们学习了如何使用Repository接口来查询,但是使用Repository接口来查询时,方法名会很长同时不利于我们写sql.

    @Query注解查询适用于所查询的数据无法通过关键字查询得到结果的查询。这种查询可以摆脱像关键字查询那样的约束,将查询直接在相应的接口方法中声明,结构更为清晰,这是Spring Data的特有实现。

    1.查询id最大的数据

    /** * 需要注意的是from后面跟的是与表名相对应的实体类名 * 同时返回值不能写* * @return */ @Query("select a from Student a where a.id = (select max(id) from Student e)") public Student getMaxId(); 测试类: @Test public void testGetMaxId() { Student s = studentRepositoryl.getMaxId(); System.out.println(s.toString()); }

    控制台了打印:说明查询成功

    2.根据name和age查询数据

    @Query("select a from Student a where a.name = ?1 and a.age = ?2") public Student getStudentByAgeAndName(String name, int age); 测试类: @Test public void testGetStudentByAgeAndName() { Student s = studentRepositoryl.getStudentByAgeAndName("赵留", 17); System.out.println(s.toString()); }

     需要注意的是:?1是占位符,需要和方法中所传递的参数顺序一致。X是从1开始。

    当然还支持命名参数(推荐使用此方式),如果

    @Query("select a from Student a where a.name = :name and a.age = :age") public Student getStudentByAgeAndName1(@Param("name") String name, @Param("age")int age); 如果冒号后面的值和我们定义的值相同。也就是上面说的name和age相同,那么也可以修改为 @Query("select a from Student a where a.name = :name and a.age = :age") public Student getStudentByAgeAndName1(String name, int age);

    3.模糊查询

    同样模糊查询同样也支持两种传参方式

    @Query("select a from Student a where a.name like %?1%") public List<Student> queryLike(String name); @Query("select a from Student a where a.name like %:name%") public List<Student> queryLike1(String name);

    4.使用原生SQL进行查询

    在@query的是将原生查询置为false,我们只需要改为true,就可以使用原生sql查询

    @Query(nativeQuery = true, value = "select count(1) from stu") public int getCount(); 测试类: @Test public void testGetCount() { int count = studentRepositoryl.getCount(); System.out.println(count); }

     5.更新删除操作

    在使用Query注解来更新和删除时,必须同时使用@Modifying注解和@Transactional注解

    @Transactional @Modifying @Query("update Student set name = :name where id = :id") public void update(String name, int id); @Test public void testUpdate() { studentRepositoryl.update("测试", 1); }

    需要注意的是@query不支持insert操作

    最新回复(0)