栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringDataJPA的自定义操作

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringDataJPA的自定义操作

自定义操作 一:jpql(原生SQL)

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

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

  1. 具名: :参数名 结合@Param注解指定参数名字
 @Query("FROM Customer where custName=:custName ")
    List 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 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 {
     
     List findByCustName(String custName);

     
     boolean existsByCustName(String custName);

     
     @Transactional
     @Modifying
     int deleteByCustId(Long custName);

     
     List findByCustNameLike(String custName);

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/894545.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号