Springboot整合 SpringDataJPA 自我练习 1.CrudRepository,PagingAndSortingRepository简单接口实现增删改查

1.导入依赖



    4.0.0

    com.jmj
    springDataJPA-Springboot
    1.0-SNAPSHOT
    
        8
        8
        UTF-8
        4.4.0
        1.1.3

        
        2.2.9.RELEASE
    
    
    
        
            
                org.springframework.boot
                spring-boot-dependencies
                ${spring-boot.version}
                pom
                import
            
        
    

    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            mysql
            mysql-connector-java
            5.1.47
        
        
            org.springframework.boot
            spring-boot-starter-test
        
        
        
            com.alibaba
            druid-spring-boot-starter
            1.2.6
        
        
            org.projectlombok
            lombok
        
    



2.application.yml

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 2001
    url: jdbc:mysql://localhost:3306/springdata_jpa?useSSL=true&useUnicode=true&characterEncoding=utf8
    type: com.alibaba.druid.pool.DruidDataSource
  jpa:
    hibernate:
      ddl-auto: update #数据库表的生成策略
    show-sql: true  #是否显示SQL
    properties:
      hibernate:
        format_sql: true #格式化SQL
    generate-ddl: true  #打印建表修改表信息

3.实体类

package com.jmj.springDataApp.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;

@Data
@Entity
@Table(name = "tb_student")
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "sid")
    private Long id;

    @Column(name = "sname",columnDefinition = "varchar(5)")
    private String name;

    @Column(name = "grade",columnDefinition = "int")
    private Integer grade;



}

4.总体结构

Springboot整合 SpringDataJPA 自我练习 1.CrudRepository,PagingAndSortingRepository简单接口实现增删改查_第1张图片

5.mapper

package com.jmj.springDataApp.mapper;

import com.jmj.springDataApp.pojo.Student;
import org.springframework.data.repository.CrudRepository;

public interface StudentCRUDMapper extends CrudRepository {
}
package com.jmj.springDataApp.mapper;

import com.jmj.springDataApp.pojo.Student;
import org.springframework.data.repository.PagingAndSortingRepository;

public interface StudentPageMapper extends PagingAndSortingRepository {

}

6.StudentCRUDMapperTest.java

package com.jmj.springDataApp.mapper;

import com.jmj.springDataApp.pojo.Student;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Supplier;

import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class StudentCRUDMapperTest {

    @Autowired
    private StudentCRUDMapper studentCRUDMapper;

    /**
     * 插入一条数据
     */
    @Test
    void save() throws Exception {
        for (int i = 0; i < 10; i++) {
            String substring = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
            int i1 = new Random().nextInt(4);
            Student student = new Student(null,substring,i1);
            Student save = studentCRUDMapper.save(student);

            System.out.println(save);
        }




    }

    @Test
    void findOne() {
        Optional byId = studentCRUDMapper.findById(5L);
        Student student = byId.orElseGet(() -> null);//查不到就是null
        System.out.println(student);
    }

    @Test
    void findAll() {
        List list = (List) studentCRUDMapper.findAll();
        System.out.println(list);
    }

    @Test
    void exist() {
        boolean b = studentCRUDMapper.existsById(7L);
        System.out.println(b);
    }

    @Test
    void findAllByIds() {
        Iterable allById = studentCRUDMapper.findAllById(Arrays.asList(1L, 2L));
        System.out.println(allById);
    }


    @Test
    void count() {
        long count = studentCRUDMapper.count();
        System.out.println(count);
    }

    @Test
    void deleteById() {
        studentCRUDMapper.deleteById(6L);//不存在会抛异常
    }

    @Test
    void deleteByEntity() {
        studentCRUDMapper.delete(new Student(3L,null,null));//不存在不会抛异常
    }

    @Test
    void name() {
    }
}

7.StudentPageMapperTest.java

package com.jmj.springDataApp.mapper;

import com.jmj.springDataApp.pojo.Student;
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.Sort;

import java.util.function.Function;

import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class StudentPageMapperTest {

    @Autowired
    private StudentPageMapper mapper;

    @Test
    void pageHelper() {
        Page page = mapper.findAll(PageRequest.of(0, 10));//0是第一页
        System.out.println("学生的集合:"+page.getContent());
        System.out.println("学生的集合总数:"+page.getTotalElements());
        System.out.println("总页数:"+page.getTotalPages());
        System.out.println("学生的集合:"+page.getSize());
        System.out.println("学生的集合:"+page.getNumber());
        System.out.println("学生的集合:"+page.getNumberOfElements());
        System.out.println("学生的集合:"+page.getSort());
        System.out.println(page.toList());
        System.out.println(page);
    }


    @Test
    void sort() {
        Sort sort = Sort.by("name").ascending();
        Iterable all = mapper.findAll(sort);
        System.out.println(all);

    }

    @Test
    void sortByPage() {
        Page name = mapper.findAll(PageRequest.of(1, 12, Sort.Direction.DESC, "name"));
        System.out.println(name.toList());
    }

    @Test
    void type_soft() {
        Sort.TypedSort sort = Sort.sort(Student.class);
        Sort ascending = sort.by(Student::getName).ascending();//升序排序
        Iterable all = mapper.findAll(ascending);
        System.out.println(all);
    }
}

你可能感兴趣的:(SpringBoot,spring,boot,后端,java)