SpringDataJPA的自定义操作

自定义操作

一:jpql(原生SQL)

a. @Query
i. 查询如果返回单个实体 就用实体对象接收 , 如果是多个需要通过集合
ii. 参数设置方式

  1. 索引 : ?数字
// 查询
     @Query("FROM Customer where custName=?1 ")
     List<Customer> findCustomerByCustName1(@Param("custName") String custName);

  1. 具名: :参数名 结合@Param注解指定参数名字
 @Query("FROM Customer where custName=:custName ")
    List<Customer> findCustomerByCustName(@Param("custName") String custName);

iii. 增删改:
5. 要加上事务的支持:
@Transactional // 通常会放在业务逻辑层上面去声明
@Modifying // 通知springdatajpa 是增删改的操作

7. 如果是插入方法:一定只能在hibernate下才支持 (Insert into
…select )

// 修改
    @Transactional //实际中加在业务逻辑上
    @Modifying   // 通知springdatajpa 是增删改的操作
    @Query("UPDATE Customer c set c.custName=:custName where c.custId=:id")
    int updateCustomer(@Param("custName") String custName,@Param("id")Long id);


    @Transactional
    @Modifying   // 通知springdatajpa 是增删改的操作
    @Query("DELETE FROM Customer c where c.custId=?1")
    int deleteCustomer(Long id);

    // 新增  JPQL
    @Transactional
    @Modifying   // 通知springdatajpa 是增删改的操作   Customer (custName)表示只插入custName
    @Query("INSERT INTO Customer (custName) SELECT c.custName FROM Customer c where c.custId=?1")
    int insertCustomerBySelect(Long id);

	//原生的sql需要加,nativeQuery = true
    @Query(value="select * FROM tb_customer where cust_name=:custName "
    ,nativeQuery = true)
    List<Customer> findCustomerByCustNameBySql(@Param("custName") String custName);

一、规定方法名

支持的查询方法主题关键字(前缀)
决定当前方法作用
只支持查询和删除
在这里插入图片描述
Repository接口中

package com.tuling.repositories;

import com.tuling.pojo.Customer;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface CustomerMethodNameRepository extends PagingAndSortingRepository<Customer,Long> {
     /**
      * 通过name查询
      * @param custName
      * @return
      */
     List<Customer> findByCustName(String custName);

     /**
      * 是否存在
      * @param custName
      * @return
      */
     boolean existsByCustName(String custName);

     /**
      * 删除
      * @param custName
      * @return
      */
     @Transactional
     @Modifying
     int deleteByCustId(Long custName);

     /**
      * 模糊查询
      * @param custName
      * @return
      */
     List<Customer> findByCustNameLike(String custName);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值