自定义操作
一:jpql(原生SQL)
a. @Query
i. 查询如果返回单个实体 就用实体对象接收 , 如果是多个需要通过集合
ii. 参数设置方式
- 索引 : ?数字
// 查询
@Query("FROM Customer where custName=?1 ")
List<Customer> findCustomerByCustName1(@Param("custName") String custName);
- 具名: :参数名 结合@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);
}