Spring Data JPA提供的查询方法已经可以解决大部分的应用场景,但是对于某些业务来说,我们还需要灵活的构造查询条件,这时就可以使用@Query注解,结合JPQL的语句方式完成查询。
jpql特点 :语法或关键字和sql语句类似, 但查询的是类和类中的属性。
(注意:jpql中不可用 select * 查询,但可以是 具体属性名)。
需要将JPQL语句配置到接口方法上
1.特有的查询:需要在dao接口上配置方法
2.在新添加的方法上,使用注解的形式配置jpql查询语句
3.注解 : @Query
package com.geor.JpaDemo.dao;
import com.geor.JpaDemo.domain.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.test.annotation.Rollback;
import java.util.List;
/**
* JpaRepository<操作的实体类类型,Id的数据类型>
* * 封装了基本CRUD操作
* JpaSpecificationExecutor<操作的实体类类型>
* * 封装了复杂查询(分页)
*
* @author kuailedetanger@163.com
* @create 2021/4/19 17:25
*/
public interface CustomerDao2 extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer>
{
@Query(value = "from Customer")
public List<Customer> findMyCustomer();
//@Query 使用jpql的方式查询。?1代表参数的占位符,其中1对应方法中的参数索引
@Query(value="from Customer where custName = ?1")
public Customer findCustomer(String custName);
/**
*
* @param custName
* @param custId
* @return
*/
//@Query 使用jpql的方式查询。?1代表参数的占位符,其中1对应方法中的参数索引
@Query(value="from Customer where custName = ?2 and custId = ?1")
public Customer findBynameAndiD(Long custId,String custName);
// @Modifying 来将该操作标识为修改查询,这样框架最终会生成一个更新的操作,而非查询
@Query(value="update Customer set custName = ?1 where custId = ?2")
@Modifying
public void updateCustomer(String custName,Long custId);
}
注意:
当@Query的nativeQuery属性配置可以使用数据库的sql查询。【false(使用jpql查询) | true(使用本地查询:sql查询)】
/**
* JpaRepository<操作的实体类类型,Id的数据类型>
* * 封装了基本CRUD操作
* JpaSpecificationExecutor<操作的实体类类型>
* * 封装了复杂查询(分页)
*
* 注解 : @Query 的属性nativeQuery :false(使用jpql查询) | true(使用本地查询:sql查询)
* @author kuailedetanger@163.com
* @create 2021/4/19 17:25
*/
public interface CustomerDao3 extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer>
{
/**
* nativeQuery : 使用本地sql的方式查询
*/
@Query(value="select * from cst_customer1",nativeQuery=true)
public List<Customer> findSql();
//@Query 使用jpql的方式查询。?1代表参数的占位符,其中1对应方法中的参数索引
@Query(value="select * from cst_customer1 where cust_name = ?2 and cust_id = ?1",nativeQuery=true)
public Customer findBynameAndi(Long custId,String custName);
}