SpringBoot 学习之整合 SpringDataJPA

项目环境:Jdk11.0.2、MySql8.0.19

一、创建普通Java项目

SpringBoot 学习之整合 SpringDataJPA_第1张图片

二、修改 pom.xml 文件


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>springboot-jpaartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>jarpackaging>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.2.6.RELEASEversion>
    parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.19version>
        dependency>
    dependencies>
project>

三、创建SpringBoot全局配置文件application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
    username: root
    password: kenewstar
  jpa:
    hibernate:
      #生成DDL语句,自动创建表
      ddl-auto: update
    #控制台打印执行的SQL语句
    show-sql: true

四、创建用户实体类User

/**
 * @Author: kenewstar
 * @Description: 用户实体类
 * @Date:Created in 2020/6/26
 */
@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String username;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

五、创建UserRepository接口继承JpaRepository接口

/**
 * @Author: kenewstar
 * @Description: 数据访问层,无需添加任何方法,只需继承JpaRepository接口即可
 * @Date:Created in 2020/6/26
 */
@Repository
public interface UserRepository extends JpaRepository<User,Integer> {

}

六、创建SpringBoot启动类

/**
 * @Author: kenewstar
 * @Description: SprnigBoot启动类
 * @Date:Created in 2020/6/26
 */
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        //springboot启动
        SpringApplication.run(App.class,args);
    }
}

七、创建测试类TestUserRepository

插入一条数据和更新一条数据均可使用save()方法,SpringDataJPA会自动判断数据库中是否存在该数据,若已存在,则更新,若不存在则插入;
SpringDataJPA源码如下:
org.springframework.data.jpa.repository.support.SimpleJpaRepository类

	/*
	 * (non-Javadoc)
	 * @see org.springframework.data.repository.CrudRepository#save(java.lang.Object)
	 */
	@Transactional
	@Override
	public <S extends T> S save(S entity) {

		if (entityInformation.isNew(entity)) {
			em.persist(entity);
			return entity;
		} else {
			return em.merge(entity);
		}
	}

SpringDataJPA测试类

import com.kenewstar.App;
import com.kenewstar.entity.User;
import com.kenewstar.repository.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
 * @Author: kenewstar
 * @Description: 测试SpringBoot整合SpringDataJPA进行增删改查
 * @Date:Created in 2020/6/26
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {App.class})
public class TestUserRepository {

    @Autowired
    private UserRepository userRepository;

    /**
     * 添加一个User
     */
    @Test
    public void testInsertUser(){

        User user = new User();
        user.setUsername("kenewstar1");
        this.userRepository.save(user);
    }

    /**
     * 根据id删除User
     */
    @Test
    public void testDelete(){
        this.userRepository.deleteById(1);
    }

    /**
     * 修改User
     */
    @Test
    public void testUpdate(){
        User user = new User();
        user.setId(2);
        user.setUsername("kenewstar2");
        this.userRepository.saveAndFlush(user);
    }

    /**
     * 查询所有
     */
    @Test
    public void findAll(){
        List<User> users = userRepository.findAll();
        for (User user:users){
            System.out.println(user.getId()+"---"+user.getUsername());
        }
    }
}

八、SpringDataJPA的接口

SpringBoot 学习之整合 SpringDataJPA_第2张图片

1.Repository接口

SpringBoot 学习之整合 SpringDataJPA_第3张图片

2.CrudRepository接口

SpringBoot 学习之整合 SpringDataJPA_第4张图片

3.PagingAndSortingRepository接口

SpringBoot 学习之整合 SpringDataJPA_第5张图片

4.JpaRepository接口

SpringBoot 学习之整合 SpringDataJPA_第6张图片

5.JpaSpecificationExecutor

SpringBoot 学习之整合 SpringDataJPA_第7张图片

创建接口继承JpaSpecificationExecutor接口

/**
 * @Author: kenewstar
 * @Description: JpaSpecificationExecutor
 * @Date:Created in 2020/6/27
 */
public interface UserRepositorySpecification extends
        JpaRepository<User,Integer>, JpaSpecificationExecutor<User> {

}

创建测试类

/**
 * @Author: kenewstar
 * @Description:
 * @Date:Created in 2020/6/27
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = App.class)
public class TestUserRepositorySepcification {

    @Autowired
    private UserRepositorySpecification userRepositorySpecification;

    /**
     * 单条件查询
     */
    @Test
    public void testSelect1(){
        //封装查询条件
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                /**
                 * 参数一:获取查询条件属性
                 * 参数二:获取查询属性的值
                 */
                Predicate pre = criteriaBuilder.equal(root.get("username"), "kenewstar2");
                return pre;
            }
        };
        //执行查询
        List<User> users = this.userRepositorySpecification.findAll(specification);
        for (User user : users){
            System.out.println(user);
        }


    }
    /**
     * 多条件查询
     */
    @Test
    public void testSelect2(){
        //封装查询条件
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                list.add(criteriaBuilder.equal(root.get("username"),"kenewstar3"));
                list.add(criteriaBuilder.equal(root.get("id"),3));
                //不能使用list.toArray()强转为 Predicate[] 类型
                Predicate predicate = criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
                return predicate;
            }
        };
        //执行查询
        List<User> users = this.userRepositorySpecification.findAll(specification);
        for (User user : users){
            System.out.println(user);
        }


    }

}

还可以进行排序查询,分页查询

九、关联查询

用户与角色关联
每个用户对应一个角色
每个角色有多个用户
(一对多关联查询)

1.创建User实体类

/**
 * @Author: kenewstar
 * @Description: 用户实体类
 * @Date:Created in 2020/6/26
 */
@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String username;

    @ManyToOne(cascade = CascadeType.MERGE) //级联操作,角色表中没有的角色,执行时进行添加操作,使用CascadeType.PERSIST
    @JoinColumn(name = "rid")   //外键
    private Role role;

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                '}';
    }
}

2.创建Role实体类

/**
 * @Author: kenewstar
 * @Description:
 * @Date:Created in 2020/6/26
 */
@Entity
@Table(name = "role")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;    //角色名称

    @OneToMany(mappedBy = "role")   //对应User对象中role属性名称
    private Set<User> users = new HashSet<>();

    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

3.创建UserRepository接口继承JpaRepository接口

package com.kenewstar.repository;

import com.kenewstar.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * @Author: kenewstar
 * @Description: 数据访问层,无需添加任何方法,只需继承JpaRepository接口即可
 */
@Repository
public interface UserRepository extends JpaRepository<User,Integer> {

}

4.创建测试类测试关联操作

import com.kenewstar.App;
import com.kenewstar.entity.Role;
import com.kenewstar.entity.User;
import com.kenewstar.repository.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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

/**
 * @Author: kenewstar
 * @Description: 测试关联操作
 * @Date:Created in 2020/6/27
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = App.class)
public class TestOneToMany {

    @Autowired
    private UserRepository userRepository;
    @Test
    public void testInsert(){
        //创建用户
        User user = new User();
        user.setId(6); //设置了Id,则执行修改用户操作
        user.setUsername("kenewstar6");
        //创建角色
        Role role = new Role();
        role.setId(2);	//设置了Id则给相应的用户添加对应的外键,不创建新的角色,未设置Id,则会在数据库中角色表添加一个新角色,User表中必须使用CascadeType.PERSIST
        role.setName("user");
        //关联操作
        user.setRole(role);
        role.getUsers().add(user);
        //持久化
        //user与role级联操作
        this.userRepository.save(user);

    }


    @Test
    public void testSelect(){
        Optional<User> optional = this.userRepository.findById(5);
        User user = optional.get();
        System.out.println(user);
        System.out.println(user.getRole().getName());
    }
    @Test
    public void findAll(){
        List<User> users = this.userRepository.findAll();
        for (User user:users){
            System.out.println(user+"---"+user.getRole().getName());
        }
    }

}

你可能感兴趣的:(JavaEE,#,SpringBoot,spring,boot)