SpringBoot+jpa实现增删改查,分页,自定义查询,jpql查询

源码:

链接:https://pan.baidu.com/s/1Uj19iyP-_80QCfliC9dD6A 
提取码:x2j9 
 

简介

JPA全称Java Persistence API.JPA通过JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
JPA是sun官方提出的java持久规范,它为java开发人员提供了一种对象/关系映射工具来管理java应用中的关系数据.
解释一下几个概念:
持久化(Persisttence):即把数据(如内存中的对象)保存到可永久保存的存储的设备中(如磁盘),持久化的主要应用是将内存中的对象存储在数据库中,或者存储在磁盘文件中.xml数据文件中等等.
持久化:将程序数据在持久状态和瞬时状态之间转换的机制.
JDBC:就是一种持久化机制,文件IO也是一种持久化机制.

1.jpa实现增删改查,分页

配置文件application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=x5
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
#update:只创建一次,数据累加
#create:每次都重新创建一次,数据替换
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL55Dialect

Pet类

package com.hxci.jcy.springboot01.domain;

import javax.persistence.*;
//表明当前是一个实体类,自动创建表t_pet与之映射,若不加name,默认创建和实体类名称一样的表pet
@Entity(name="t_pet")
public class Pet {

    //注解id,并设置主键--》自动增加
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private int id;

    // @Column标识是一个普通的字段
    @Column
    private String name;

    @Column
    private String color;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Pet{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", color='" + color + '\'' +
                '}';
    }

    public Pet(int id, String name, String color) {
        this.id = id;
        this.name = name;
        this.color = color;
    }
    public Pet() {

    }
}

PetDao类

package com.hxci.jcy.springboot01.dao;

import com.hxci.jcy.springboot01.domain.Pet;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

//JpaRepository
//T:表示具体操作的实体类,Pet
//ID:表示主键的类型,Integer
public interface PetDao extends JpaRepository {
    /*
        自定义查询
        1、什么时候自定义查询
        JpaRepository接口当中提供的方法不能正常满足实际业务需求,此时我们需要一个自定义查询
        2.方法定义注意事项
        方法的返回值是根据实际的业务需求定义:List Pet
        方法的名称必须满足规范findByXxx,findBy固定开始,Xxx属性名称
        参数列表根据需求来定义
     */
    //定义通过pname查询
    List findByName(String name);
    //定义通过color查询
    List findByColor(String color);
    //定义通过pname和color联合查询
    List findByNameAndColor(String name,String color);
    //根据id查询,查询id在一个范围内的Pet对象
    List findByIdBetweenOrderById(Integer minId, Integer maxId);
    //去测试类中调用

    //jpql查询
   /*
        sql查询:select * from t_pet
        jpql查询:from com.hxci.jcy.springboot01.domain.Pet
                select A from com.hxci.jcy.springboot01.domain.Pet A(别名)
     */
    //@Query(value = "from pet.domain.Pet")
    @Query("select A from com.hxci.jcy.springboot01.domain.Pet A")
    List loadPetsList();

    /*
        //1、查询的数据封装到了Object[]中,而不是Pet
        sql:select name,color from t_pet
        spql:select name,color from com.hxci.jcy.springboot01.domain.Pet"
     */
    @Query("select name,color from com.hxci.jcy.springboot01.domain.Pet")
    List loadPetsList2();

    //2.查询的数据封装到Pet
    @Query("select new com.hxci.jcy.springboot01.domain.Pet(id,name,color) from com.hxci.jcy.springboot01.domain.Pet pet")
    List loadPetsList3();
}

测试类

package com.hxci.jcy.springboot01;

import com.hxci.jcy.springboot01.dao.PetDao;
import com.hxci.jcy.springboot01.domain.Pet;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@SpringBootTest(classes = Springboot01Application.class)
class Springboot01ApplicationTests {

    @Test
    void contextLoads() {
        System.out.println("table 创建成功");
    }


    @Autowired
    PetDao petDao;

    /*
    save()方法:
        1.如果没有设置id,则进行一个insert添加操作
        2.如果设置id,
            1.根据指定的id先去查询,若查到指定id值存,进行一个update更新操作
            2.若没查到指定id,进行一个添加操作
     */
    @Test
    void addPet() {
        System.out.println("添加成功");
        Pet pet = new Pet();
        //id自增,不需要设置
        pet.setName("小超");
        pet.setColor("黑色");
        petDao.save(pet);
    }

    //添加时ID存在则修改
    @Test
    void updatePet() {
        System.out.println("更新成功");
        Pet pet = new Pet();
        pet.setId(12);
        pet.setName("小超666");
        pet.setColor("黑色");
        petDao.save(pet);
    }

    /*
        查询操作,根据id查询
        findById()是JpaRepository接口提供的
        查询到的内容封装到了Optional对象中
        get()方法是Optional对象中的,获得Pet对象
        查询的对象不存在,返回一个异常
     */
    @Test
    void findPet() {
        Optional optional = petDao.findById(1);
        Pet pet = optional.get();
        System.out.println(pet.getId() + " " + pet.getName() + " " + pet.getColor());
    }

    /*
    列表查询 返回的是列表集合
    findAll(); 没有指定任何的参数,查询列表
    findAll(); 在使用的时候可以指定参数。 sort对象,指定排序字段,升序或者降序。
     */
    @Test
    void findAllPets() {
        /*List pets=petDao.findAll();
        //有toString方法,可以直接输出pet对象
        for (Pet pet : pets) {
            System.out.println(pet);
        }
    }*/
        //查找到的数据按name升序排序
        List name = petDao.findAll(Sort.by("name"));
        for (Pet pet : name) {
            System.out.println(pet.getName());
        }
    }

    @Test
    void findAllPetsWithPage() {
        /*
        Pageable : 接口类型:
        Pageable : 接口的实现对象: 实现类不是直接new,构造器protect
                  PageRequest: 类中提供了of方法,返回本类对象:
                  of();方法,static 静态方法:
                  参数一:
                  page: 查询第一页,用户指定: 0代表第一页
                  size: 当前页显示的记录数:
                  Sort.Direction.ASC  指定升序排序
                  Sort.Direction.DESC 指定降序排序
                  propertices :指定具体哪一个属性进行排序


         */
        //Pageable 对象封装了一些分页相关的参数:
        Pageable pageable = PageRequest.of(0,2,Sort.Direction.DESC,"id");
        Page pets = petDao.findAll(pageable);
        for (Pet pet : pets) {
            System.out.println(pet);
        }
        //获得分页的相关信息:
        //pets.getTotalElements();获得元素的个数
        //int totalPages = pets.getTotalPages();//获得页数
    }

    /*
    删除操作
    delete(pet);传递pet对象,删除传递对象
    删除的具体步骤:
    (1)先根据id进行一个查询。
    (2)执行delete操作
     */
    @Test
    void deletePet() {
      /* Pet pet = new Pet();
       pet.setId(2);
       petDao.delete(pet);*/
      petDao.deleteById(3);
    }


    @Test
    void findName(){
        //通过pname查询
        List list = petDao.findByName("小松");
        System.out.println(list);
        //通过color查询
        List listColor = petDao.findByColor("黑色");
        System.out.println(listColor);
        //定义通过pname和color联合查询
        List byNameAndColor = petDao.findByNameAndColor("小黑", "黑色");
        System.out.println(byNameAndColor);
        //查询id:1-4之间的
        List byIdBetweenOrderById = petDao.findByIdBetweenOrderById(1, 4);
        System.out.println(byIdBetweenOrderById);

    }

    //jpql查询
    @Test
    void jpqlFind(){
        List pets = petDao.loadPetsList();
        System.out.println(pets);
    }

    @Test
    void test(){
        List objects = petDao.loadPetsList2();
        for (Object[] object : objects) {
            System.out.println(Arrays.toString(object));
        }
    }

    @Test
    void test1(){
        List pets = petDao.loadPetsList3();
        System.out.println(pets);
    }


}

2.自定义查询

PetDao接口

package com.hxci.jcy.springboot01.dao;

import com.hxci.jcy.springboot01.domain.Pet;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

//JpaRepository
//T:表示具体操作的实体类,Pet
//ID:表示主键的类型,Integer
public interface PetDao extends JpaRepository {
    /*
        自定义查询
        1、什么时候自定义查询
        JpaRepository接口当中提供的方法不能正常满足实际业务需求,此时我们需要一个自定义查询
        2.方法定义注意事项
        方法的返回值是根据实际的业务需求定义:List Pet
        方法的名称必须满足规范findByXxx,findBy固定开始,Xxx属性名称
        参数列表根据需求来定义
     */
    //定义通过pname查询
    List findByName(String name);
    //定义通过color查询
    List findByColor(String color);
    //定义通过pname和color联合查询
    List findByNameAndColor(String name,String color);
    //根据id查询,查询id在一个范围内的Pet对象
    List findByIdBetweenOrderById(Integer minId, Integer maxId);
    //去测试类中调用

    //jpql查询
   /*
        sql查询:select * from t_pet
        jpql查询:from com.hxci.jcy.springboot01.domain.Pet
                select A from com.hxci.jcy.springboot01.domain.Pet A(别名)
     */
    //@Query(value = "from pet.domain.Pet")
    @Query("select A from com.hxci.jcy.springboot01.domain.Pet A")
    List loadPetsList();

    /*
        //1、查询的数据封装到了Object[]中,而不是Pet
        sql:select name,color from t_pet
        spql:select name,color from com.hxci.jcy.springboot01.domain.Pet"
     */
    @Query("select name,color from com.hxci.jcy.springboot01.domain.Pet")
    List loadPetsList2();

    //2.查询的数据封装到Pet
    @Query("select new com.hxci.jcy.springboot01.domain.Pet(id,name,color) from com.hxci.jcy.springboot01.domain.Pet pet")
    List loadPetsList3();
}

你可能感兴趣的:(java)