SpringBoot Actual | Access Mysql database using Spring Data JPA

Keywords: Java Spring MySQL Hibernate

Wechat Public Number: An Excellent Abandoned Person
If you have any questions or suggestions, please leave a message in the background. I will try my best to solve your problems.

Preface

As the title, today we introduce the use of Spring Data JPA.

What is Spring Data JPA

Before introducing Spring Data JPA, we first introduce Hibernate. Hibernate uses Object-Relation Mapping technology to realize data access. O/R mapping maps domain model classes and database tables. It realizes the ability of table data operation through program operation objects, so that data access operations need not pay attention to database related technology.

Hibernate dominates the JPA specification of EJB 3.0, the Java Persistence API. JPA is a standard protocol based on O/R mapping (the latest version is JPA 2.1). The so-called specification only defines standard regulations (such as annotations, interfaces) and does not provide implementations. Software providers can implement them in accordance with standard specifications, while users only need to use them in the way defined in the specification, instead of dealing with the implementations of software providers. The main implementation of JPA is accomplished by Hibernate, Eclipse Link and OpenJPA. We only need to use JPA to develop, regardless of which development method is the same.

Spring Data JPA is a sub-project of Spring Data, which greatly reduces the amount of code JPA as a data access scheme through JPA-based Repository.

In short, JPA is an ORM specification, but it does not provide an ORM implementation, while Hibernate is an ORM framework that provides an ORM implementation.

Dead work

  • IDEA
  • JDK1.8
  • SpringBoot 2.1.3

The dependencies introduced by the pom.xml file are as follows:

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.nasus</groupId>
    <artifactId>jpa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>jpa</name>
    <description>jpa Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!-- JPA rely on -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- web rely on -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- mysql Connection class -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- lombok rely on -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- Unit test dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Simply put, add JPA dependencies; mysql connection classes are used to connect data; web startup classes, but all web applications need to rely on them; lombok is used to simplify entity classes. I won't read this old introduction. SpringBook Actual Warfare (3) | Use LomBok

application.yaml configuration file

spring:
# Database correlation
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=true
    username: root
    password: 123456
# JPA correlation
  jpa:
    hibernate:
      ddl-auto: update   #ddl-auto: Set create to indicate that the table is rebuilt every time
    show-sql: true

repository (dao) layer

package com.nasus.jpa.repository;

import com.nasus.jpa.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

/**
 * Project Name:springboot_jpa_demo <br/>
 * Package Name:com.nasus.jpa.repository <br/>
 * Date:2019/2/19 21:37 <br/>
 * <b>Description:</b> TODO: Describe the role of this class <br/>.
 * @author <a href="turodog@foxmail.com">nasus</a><br/>
 */
@Repository
public interface StudentRepository extends JpaRepository<Student,Integer>, CrudRepository<Student, Integer> {
}

From the figure above, you can see that Jpa Repository inherited from PangingAndSorting Repository and CrudRepository.

CrudRepository provides the basic add-delete check PagingAndSorting Repository provides paging and sorting methods; JpaRepository provides the methods JPA needs. When using it, you can select which interface to inherit according to your specific needs.

The benefits of using these interfaces are:

  1. By inheriting these interfaces, Spring can find a customized database operation interface and generate proxy classes, which can be injected into the Spring container.
  2. It can be generated by proxy classes without writing related sql operations

service level

package com.nasus.jpa.service;

import com.nasus.jpa.entity.Student;
import java.util.List;

/**
 * Project Name:springboot_jpa_demo <br/>
 * Package Name:com.nasus.jpa.service <br/>
 * Date:2019/2/19 21:41 <br/>
 * <b>Description:</b> TODO: Describe the role of this class <br/>.
 * @author <a href="turodog@foxmail.com">nasus</a><br/>
 */
public interface StudentService {

    Student save(Student student);

    Student findStudentById(Integer id);

    void delete(Integer id);

    void updateStudent(Student student);

    List<Student> findStudentList();
}

Implementation class:

package com.nasus.jpa.service.impl;

import com.nasus.jpa.entity.Student;
import com.nasus.jpa.repository.StudentRepository;
import com.nasus.jpa.service.StudentService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Project Name:springboot_jpa_demo <br/>
 * Package Name:com.nasus.jpa.service.impl <br/>
 * Date:2019/2/19 21:43 <br/>
 * <b>Description:</b> TODO: Describe the role of this class <br/>.
 * @author <a href="turodog@foxmail.com">nasus</a><br/>
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    /**
     * Preserving Student Information
     * @param student
     * @return
     */
    @Override
    public Student save(Student student) {
        return studentRepository.save(student);
    }

    /**
     * Query the Student Information Based on Id
     * @param id
     * @return
     */
    @Override
    public Student findStudentById(Integer id) {
        return studentRepository.findById(id).get();
    }

    /**
     * Delete student information
     * @param id
     */
    @Override
    public void delete(Integer id) {
        Student student = this.findStudentById(id);
        studentRepository.delete(student);
    }

    /**
     * Update student information
     * @param student
     */
    @Override
    public void updateStudent(Student student) {
        studentRepository.save(student);
    }

    /**
     * Query Student Information List
     * @return
     */
    @Override
    public List<Student> findStudentList() {
        return studentRepository.findAll();
    }
}

controller layer builds restful API

package com.nasus.jpa.controller;

import com.nasus.jpa.entity.Student;
import com.nasus.jpa.service.StudentService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Project Name:springboot_jpa_demo <br/>
 * Package Name:com.nasus.jpa.controller <br/>
 * Date:2019/2/19 21:55 <br/>
 * <b>Description:</b> TODO: Describe the role of this class <br/>.
 * @author <a href="turodog@foxmail.com">nasus</a><br/>
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @PostMapping("/save")
    public Student saveStudent(@RequestBody Student student){
        return studentService.save(student);
    }

    @GetMapping("/{id}")
    public Student findStudentById(@PathVariable("id") Integer id){
        return studentService.findStudentById(id);
    }

    @GetMapping("/list")
    public List<Student> findStudentList(){
        return studentService.findStudentList();
    }

    @DeleteMapping("/{id}")
    public void deleteStudentById(@PathVariable("id") Integer id){
        studentService.delete(id);
    }

    @PutMapping("/update")
    public void updateStudent(@RequestBody Student student){
        studentService.updateStudent(student);
    }
}

test result

Other interfaces have passed the postman test, no problem.

Source download: https://github.com/turoDog/De...

Posterior language

The above is a tutorial for SpringBoot to access Mysql databases using Spring Data JPA. Finally, if you are interested in Python and Java, please pay attention to a wave of two-dimensional codes for a long time. I will try to bring you value. If you think this article is even a little helpful to you, please help to look good and let more people know.

In addition, free learning materials are available after 1024 is sent. For more information, please refer to this old article: Python, C++, Java, Linux, Go, Front-end, Algorithmic Data Sharing

Posted by Nhoj on Tue, 19 Feb 2019 08:21:20 -0800