springDataJPQL实现增删改查及分页,原生sql查询,根据方法命名规则实现查询

一、使用方法

1、在dao中定义开一个方法,使用方法的参数设置jpql,并且使用方法的返回值接受查询结果,在方法上添加@query注解,在注解中写jpql语句进行增删改查,测试

2、使用原生的sql语句:dao中定义一个方法,在方法中添加@query注解,在注解中添加原生sql语句,并且添加一个属性:nativeQuery=true,测试

3、方法命名规则查询:

  通过以肯定的规则,定义一个方法,框架本身就可以根据方法名生成一块个sql语句进行查询,规则:

    1、必须以findBy开头

    2、查询某个字段,findBy后跟实体类的属性名称

    3、如果有多个条件,就在方法后加And后跟实体类的属性名

    4、方法的参数对应查询的定义

    5、返回值根据返回值的数据类型定义;如果是分页查询,在方法中添加一个参数Pageable即可

二、、编写实现类

package cn.zrf.jpa.entity;

import javax.persistence.*;

@Entity
@Table(name = "cust_customer")
public class Customer {
    // 配置主键自增的策略
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    @Column(name="cust_id")
    private long custId;
    @Column(name="cust_name")
    private String custName;
    @Column(name="cust_source")
    private String custSource;
    @Column(name="cust_indutry")
    private String custIndutry;
    @Column(name="cust_level")
    private String custLevel;
    @Column(name="cust_address")
    private String custAddress;
    @Column(name="cust_phone")
    private String custPhone;

    @Override
    public String toString() {
        return "Customer{" +
                "custId=" + custId +
                ", custName=‘" + custName + ‘\‘‘ +
                ", custSource=‘" + custSource + ‘\‘‘ +
                ", custIndutry=‘" + custIndutry + ‘\‘‘ +
                ", custLevel=‘" + custLevel + ‘\‘‘ +
                ", custAddress=‘" + custAddress + ‘\‘‘ +
                ", custPhone=‘" + custPhone + ‘\‘‘ +
                ‘}‘;
    }

    public long getCustId() {
        return custId;
    }

    public void setCustId(long custId) {
        this.custId = custId;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getCustSource() {
        return custSource;
    }

    public void setCustSource(String custSource) {
        this.custSource = custSource;
    }

    public String getCustIndutry() {
        return custIndutry;
    }

    public void setCustIndutry(String custIndutry) {
        this.custIndutry = custIndutry;
    }

    public String getCustLevel() {
        return custLevel;
    }

    public void setCustLevel(String custLevel) {
        this.custLevel = custLevel;
    }

    public String getCustAddress() {
        return custAddress;
    }

    public void setCustAddress(String custAddress) {
        this.custAddress = custAddress;
    }

    public String getCustPhone() {
        return custPhone;
    }

    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }
}

  

三、编写dao

package cn.zrf.jpa.dao;

import cn.zrf.jpa.entity.Customer;
import org.springframework.data.domain.Pageable;
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 java.util.List;

public interface CustomerDao extends JpaRepository<Customer,Long>,JpaSpecificationExecutor<Customer> {
    //查询全部
    @Query("from Customer")
    List<Customer> getAllCustomer();
    //查询全部并分页
    @Query("from Customer ")
    List<Customer> getAllCustomerByPage(Pageable pageable);
    //条件查询(根据ID查询)
    @Query("from Customer where cust_id = ?")
    Customer getCustomerById(Long id);
    //根据地址,姓名模糊查询
    @Query("from Customer where custAddress like ? and custName like ?")
    List<Customer> getCustList(String address,String custName);
    //根据ID进行局部更新操作
    @Query("update Customer set cust_name=? where custId=?")
    @Modifying
    void getUpdateById(String name,Long id);
    //原生sql语句模糊查询操作
    @Query(value = "select * from cust_customer where cust_name like ?",nativeQuery = true)
    List<Customer> getCustomerListByNative(String name);
    //方法命名规则查询
    /**1 应该使用findBy开头
     * 2 查询某个字段  findBy后跟实体类的属性的名称
     * 3 如果有多个条件   就在方法后加And+实体类的属性名
     * 4  方法的参数 对应查询的定义
     * 5 返回值根据返回的数据类型定义
     * 6 如果需要分页查询   在方法中添加一个参数Pageable 即可
     */
    //根据ID查询
    Customer findByCustId(Long id);
    //根据姓名,地址进行模糊查询
    List<Customer> findByCustNameLikeAndCustAddressLike(String name,String address);
    //分页查询
    List<Customer> findByCustAddressLike(String address, Pageable pageable);
}

  

四、测试类

package cn.jpa.test;

import cn.zrf.jpa.dao.CustomerDao;
import cn.zrf.jpa.entity.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.annotation.Commit;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.awt.print.Pageable;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestJpql {
    @Autowired
    CustomerDao customerDao;
    //查询全部
    @Test
    public void getAllCustomerTest(){
        List<Customer> list = customerDao.getAllCustomer();
        for (Customer customer:list){
            System.out.println(customer);
        }
    }
    //查询全部并分页
    @Test
    public void getAllCustomerByPageTest(){
        List<Customer> list = customerDao.getAllCustomerByPage(new PageRequest(0, 3));
        for (Customer customer:list){
            System.out.println(customer);
        }
    }
    //根据ID查询
    @Test
    public void getCustomerByIdTest(){
        Customer customer = customerDao.getCustomerById(1l);
        System.out.println(customer);
    }
    //根据地址,姓名进行模糊查询
    @Test
    public void getCuseListTest(){
        List<Customer> custList = customerDao.getCustList("%京%", "%长%");
        for (Customer customer:custList){
            System.out.println(customer);
        }
    }
    //根据ID进行局部更新操作
    @Test
    @Transactional
    @Commit
    public void getUpdateByIdTest(){
        customerDao.getUpdateById("张无忌",3l);
    }
    //原生sql语句模糊查询
    @Test
    public void getCustomerByNativeTest(){
        List<Customer> list = customerDao.getCustomerListByNative("%长%");
        for (Customer customer:list){
            System.out.println(customer);
        }
    }
    //方法命名规则查询测试
    //根据ID查询
    @Test
    public void findByIdTest(){
        Customer customer = customerDao.findByCustId(1L);
        System.out.println(customer);
    }
    //根据地址,姓名进行模糊查询
    @Test
    public void findByCustNameLikeAndAddressLike(){
        List<Customer> list = customerDao.findByCustNameLikeAndCustAddressLike("%张%","%京%");
        for (Customer customer:list){
            System.out.println(customer);
        }
    }
    //根据地址进行分页查询
    @Test
    public void findByCustAddressLike(){
        List<Customer> list = customerDao.findByCustAddressLike("%京%", new PageRequest(0, 3));
        for (Customer customer:list){
            System.out.println(customer);
        }
    }
}

  

原文地址:https://www.cnblogs.com/zhangrongfei/p/11391177.html

时间: 2024-08-06 01:32:30

springDataJPQL实现增删改查及分页,原生sql查询,根据方法命名规则实现查询的相关文章

SpringBoot JPA实现增删改查、分页、排序、事务操作等功能

今天给大家介绍一下SpringBoot中JPA的一些常用操作,例如:增删改查.分页.排序.事务操作等功能.下面先来介绍一下JPA中一些常用的查询操作: //And --- 等价于 SQL 中的 and 关键字,比如 findByHeightAndSex(int height,char sex): public List<User> findByHeightAndSex(int height,char sex); // Or --- 等价于 SQL 中的 or 关键字,比如 findByHeig

用SpringBoot+MySql+JPA实现对数据库的增删改查和分页

使用SpringBoot+Mysql+JPA实现对数据库的增删改查和分页      JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中.  使用Springboot和jpa对数据库进行操作时,能够大大减少我们的工作量,在jpa中,已经在底层封装好了增删查的功能和sql语句,可以使我们进行快速开发 项目流程 一.新建一个项目 二.配置文件 #数据源配置 spring.dat

SpringBoot-Vue实现增删改查及分页小DEMO

前言 主要通过后端 Spring Boot 技术和前端 Vue 技术来简单开发一个demo,实现增删改查.分页功能以及了解Springboot搭配vue完成前后端分离项目的开发流程. 开发栈 前端 开发工具:WebStorm 开发框架:vue + axios 包管理工具: npm 打包工具:webpack 后端 开发工具:IDEA 开发框架:Springboot + mybatis 打包工具:maven 数据库: MySQL PS:假设以上的的工具你都安装好啦,写CRUD小DEMO时进坑了,这篇

web day19 Service层处理事务(利用ThreadLocal),TxQueryRunner小工具,单表练习(增删改查操作),分页

Service事务 DAO中不是处理事务的地方,因为DAO中的每个方法都是对数据库的一次操作 在Service中不应该出现Connection,它应该只在DAO中出现, 因为它是JDBC的东西,JDBC的东西是用来连接数据库的 修改JdbcUtils 我们把对事务的开启和关闭放到JdbcUtils中,在Service中调用JdbcUtils的方法来完成事务的处理, 但在Service中就不会再出现Connection这一"禁忌"了. 代码 public class JdbcUtils

家庭记账管理系统的增删改查,分页列表显示

上次登陆的时候也已经学习了增加的功能,这次再回忆一下 1.增 前端代码add.jsp中form表单把刷新后界面的地址与后面的action对象中结合起来,通过struts.xml配置文件进行跳转 1.1form表单 <FORM id=form1 name=form1 action="${pageContext.request.contextPath }/customer_add.action" method=post> 1.2 customerAction类中,add方法,返

面向对象---封装增删改查+数据分页

<meta charset="UTF-8"> <?php class F{ public $locahost; public $name; public $pwd; public $database; public function __construct($locahost,$name,$pwd,$database) { $this->locahost = $locahost; $this->name = $name; $this->pwd = $

Spring mvc整合mybatis基于mysql数据库实现用户增删改查及其分页显示的完整入门实例【转】

Spring mvc整合mybatis例子, 基于mysql数据库实现对用户的增.删.改.查,及分页显示的完整例子. 查询显示用户 添加用户 更新用户 官方验证: 项目截图 必须修改applicationContext.xml中mysql的配置为本地的,否则启动失败. 另外jar包多一个ehcache.jar无关紧要,删除即可. 1. 使用阿里巴巴Druid连接池(高效.功能强大.可扩展性好的数据库连接池.监控数据库访问性能.支持Common-Logging.Log4j和JdkLog,监控数据库

VS2012里面使用EF框架的增删改查和分页的方法

public class BaseRepository<T> where T : class    {        //实例化EF框架        DataModelContainer db = new DataModelContainer(); //添加        public T AddEntities(T entity)        {            db.Entry<T>(entity).State = EntityState.Added;        

一个Solr搜索实例,增删改查+高亮+分页

今天个人coding的模块测试,所以闲暇之余继续研究solr,然后顺带写了一个实例,随便搞的,solr真心不熟,期待认识热爱搜索的朋友,共同进步. 1.配置schema.xml文件[solr\collection1\conf\目录下] 因为schema默认定义了一些Field,我们这里选取[id,title,description, author]这几个属性,将id主键type配置为string,其它几个type配置为自定义的ik分词器 <field name="id" type