Using JPA spring boot operation in the database

Foreword

Spring boot of the students use the JPA will feel his strong, simply artifacts in general, popular to say, you do not need to write sql, which help you save a lot of time, so let's take this down together to experience artifact it.

First, add the pom in dependence

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

Second, the project configuration

Fill JPA database and configuration information (such dev and prod two environments is common) in application.yml in the following example:

# Multi-environment configuration 
the Spring: 
  Profiles: 
    the Active: Prod 

# generic data source configuration 
  the DataSource: 
    Driver , class and name: com.mysql.cj.jdbc.Driver 
    url: jdbc: MySQL: // localhost: 3306 / student_info serverTimezone = GMT? 2B8% 
    username: root 
    password: root 
    Hikari: 
      maximum -pool-size: 20 
      Minimum -idle: 5 
  # JPA configuration 
  JPA: 
    Hibernate: 
      DDL - Auto: the Create 
    Show -sql: to true

Description: When debugging interfaces, ddl-auto jpa in: To change update, otherwise the data will be cleared each time you run Oh!

After writing a good project configuration, where we can start the project, you will be given as follows:

 

 

 This is because I did not create this library cause, then we put together to create the library, and then we restart the project is not being given, and also help us show the creation sql statement is not very like it, ha ha

 

 

Third, the operation of the database

In front of the basic project to build a complete, let through a series of CRUD operations, to complete the operation of the database.

1. Create an entity

Create a class called Student, examples are as follows:

package com.rongrong.springboot.demo.student;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * @author rongrong
 * @version 1.0
 * @description:
 * @date 2019/12/30 21:24
 */
@Entity
public class Student {

    //主键ID
    @Id
    //自增型
    @GeneratedValue
    private Integer id;
    private String name;
    private Integer age;
    private String sex;
    private String email;
}

2、数据库操作逻辑编写

 

 

 创建一个名为StudentResponstory的接口,继承JPAResponstory,示例如下:

package com.rongrong.springboot.demo.student;

import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @author rongrong
 * @version 1.0
 * @description:
 * @date 2019/12/30 22:20
 */
public interface StudentResponstory extends JpaRepository<Student,Integer> {
}

创建一个名为StudentController的类,通过增删改查操作,来实现库的操作逻辑,具体示例代码如下:

package com.rongrong.springboot.demo.student;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author rongrong
 * @version 1.0
 * @description:
 * @date 2019/12/30 20:40
 */
@RestController
public class StudentController {

    @Autowired
    StudentResponstory studentResponstory;

    /**
     * 查询所有学生列表
     *
     * @return
     */
    @GetMapping("/students")
    public List<Student> sudentFindAll() {
        return studentResponstory.findAll();
    }

    /**
     * 新增一个学生
     *
     * @param name
     * @param age
     * @param sex
     * @param email
     * @return
     */
    @PostMapping("/studentAdd")
    public Student sudentAdd(@RequestParam("name") String name, @RequestParam("age") Integer age,
                             @RequestParam("sex") String sex, @RequestParam("email") String email) {
        Student student = new Student();
        student.setName(name);
        student.setAge(age);
        student.setSex(sex);
        student.setEmail(email);
        //保存和更新都用该方法
        return studentResponstory.save(student);
    }

    /**
     * 通过iD查找一个学生
     *
     * @param id
     * @return
     */
    @GetMapping("/sudentFindOne/{id}")
    public Student sudentFindOne(@PathVariable("id") Integer id) {
        return studentResponstory.findOne(id);
    }

    /**
     * 通过ID更新一个学生信息
     *
     * @param id
     * @param name
     * @param age
     * @param sex
     * @param email
     * @return
     */
    @PutMapping("/sudentUpdate/{id}")
    public Student sudentUpdate(@PathVariable("id") Integer id, @RequestParam("name") String name, @RequestParam("age") Integer age,
                                @RequestParam("sex") String sex, @RequestParam("email") String email) {
        Student student = new Student();
        student.setId(id);
        student.setName(name);
        student.setAge(age);
        student.setSex(sex);
        student.setEmail(email);
        //保存和更新都用该方法
        return studentResponstory.save(student);
    }

    /**
     * 通过ID删除一个学生
     *
     * @param id
     */
    @DeleteMapping("/sudentDelete/{id}")
    public void sudentDelete(@PathVariable("id") Integer id) {
        studentResponstory.delete(id);
    }

    /**
     * 通过年龄查询学生
     *
     * @param age
     * @return
     */
    @GetMapping("/sudentFindByAge/{age}")
    public List<Student> sudentFindByAge(@PathVariable("age") Integer age) {
        return studentResponstory.findByAge(age);
    }

}

通过年龄查询学生查询时,需要在接口中添加如下方法:

package com.rongrong.springboot.demo.student;

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

/**
 * @author rongrong
 * @version 1.0
 * @description:
 * @date 2019/12/30 22:20
 */
public interface StudentResponstory extends JpaRepository<Student,Integer> {
    List<Student> findByAge(Integer age);
}

再次启动项目,通过postman进行逐一测试,即可。

项目启动效果图

 

 

postman效果图

到此,spring boot中jpa的使用介绍完,有兴趣的同学可以自行尝试。

 

Guess you like

Origin www.cnblogs.com/longronglang/p/12122220.html