Spring Data JPA :自定义JPQL查询

本文介绍如何使用SpringData JPA中的@Query注解配合JPQL进行复杂查询,包括自定义查询方法、参数绑定及本地SQL查询的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值