Spring Data JPA查询

接口定义的方法进行查询

  1. 继承 JpaRepository 的后方法
  2. 继承 JpaSpecificationExecutor后的方法

使用 JPQL 方式查询

public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
    //案例:根据客户名称查询客户
    @Query(value = "from Customer where custName = ?")
    public Customer findJpql(String custName);

    //根据客户名称和客户id查询客户
	//对于多个占位符参数:
	//   赋值时候,默认的情况下,占位符的位置需要和方法参数中的位置保持一致
	//可以指定占位符参数的位置
	//   ? 索引的方式:指定此占位数的取值来源(在jpql语句中)
    @Query(value = "from Customer where custName = ? and custId = ?")
    public Customer findCustNameAndId(String name,Long id);


    //案例:根据 id 更新客户的名称
    //执行 update 需要声明此方法是用来进行更新操作
	//	@Modifying:代表当前执行的方法是更新操作
    @Query(value = "update Customer set custName = ?2 where id = ?1")
    @Modifying
    public void updateCustomer(long id,String name);
}

使用原生SQL查询

public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
     // @Query:配置sql查询(value:配置sql语句)
     // @nativeQuery:查询方式(false:jpql查询(默认)  true:sql查询)
    @Query(value = "select * from cst_customer",nativeQuery = true)
    public List<Object[]> findSql();

    //根据用户名模糊匹配查询(sql)
    @Query(value = "select * from cst_customer where cust_name like ?",nativeQuery = true)
    public List<Object[]> findByName(String name);

方法命名规则查询

     // findBy + 属性名称(根据属性名称进行完全匹配查询)
     // findBy + 属性名称 + 查询方式(Like | isnull)
     // 多条件查询:
     // findBy + 属性名 + 查询方式 + 多条件的连接符(and|or)  + 属性名 + 查询方式
    public Customer findByCustName(String custName);
    
    public List<Customer> findByCustNameLike(String custName);

    //使用客户名称和客户所属行业精准匹配的查询
    public Customer findByCustNameLikeAndCustIndustry(String name,String industry);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值