用Spring Data JPA提供的查询方法已经可以解决大部分的应用场景,但是对于某些业务来说,我们还需要灵活的构造查询条件,这时就可以使用@Query注解,结合JPQL的语句方式完成查询
@Query 注解的使用非常简单,只需在方法上面标注该注解,同时提供一个JPQL查询语句即可
此外,也可以通过使用 @Query 来执行一个更新操作,为此,我们需要在使用 @Query 的同时,用 @Modifying 来将该操作标识为修改查询,这样框架最终会生成一个更新的操作,而非查询
package com.ytkj.dao; import com.ytkj.entity.Customer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; /** * JpaRepository<实体类类型,主键类型>:用来完成基本CRUD操作 * JpaSpecificationExecutor<实体类类型>:用于复杂查询(分页等查询操作) */ public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> { /** * 根据客户名称查询 * 使用jpql查询: * from Customer where custName=? * 使用注解 */ @Query(value = "from Customer where custName=?") Customer findByName(String custName); /** * jpql占位符 * 根据id和名称查询 * 多个占位符的位置默认情况下需要和方法中的参数位置保持一致, * 也可以指定占位符参数的位置 * ? 索引 * @Query(value = "from Customer where custId=?2 and custName=?1") * Customer findByNameAndId(String custName,Long id); * @param id * @param custName * @return */ @Query(value = "from Customer where custId=? and custName=?") Customer findByNameAndId(Long id,String custName); /** * 根据id更新名称 */ @Query(value = "update Customer set custName=? where custId =? ") @Modifying//此注解表示更新操作 void updateById(String name,Long id); }
import com.ytkj.dao.CustomerDao; import com.ytkj.entity.Customer; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class)//声明spring提供的单元测试环境 @ContextConfiguration(locations = "classpath:applicationContext.xml")//指定spring容器的配置信息 public class SpringdatajpqlTest { @Autowired CustomerDao customerDao; /** * 根据id查询 */ @Test public void findByName(){ Customer customer = customerDao.findByName("zhechaochao"); System.out.println(customer); } /** * 根据id和名称查询 */ @Test public void findByNameAndId(){ Customer customer = customerDao.findByNameAndId(1L,"zhechaochao1"); System.out.println(customer); } /** * 根据id更新 */ @Test @Transactional//添加事务,使用jpql更新或者删除操作需要添加事务,否则或报错,默认会执行结束后,回滚事务 @Rollback(value = false)//设置是否自动回滚 public void updateById(){ customerDao.updateById("者超超",1L); } }
原文:https://www.cnblogs.com/yscec/p/12004144.html