Wechat official account: If you have any questions or suggestions, please leave a message on the background. I will try my best to solve your problems.

preface

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

What is Spring Data JPA

Before introducing Spring Data JPA, let’s start with Hibernate. Hibernate uses object-relation Mapping technology to realize data access. O/R Mapping is to map the domain model class to the table of the database, and realize the ability of table data operation through the program operation Object, so that data access operation does not need to pay attention to the database related technology.

Hibernate dominates the EJB 3.0 JPA specification, which stands for 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 and interfaces), but does not provide implementation. The software provider can implement them according to the standard specification, and users only need to use them in the way defined in the specification, without dealing with the implementation of the software provider. The main implementations of JPA are Done by Hibernate, EclipseLink, OpenJPA, etc. As long as we use JPA to develop, no matter which development method is the same.

Spring Data JPA is a subproject of Spring Data that dramatically reduces the amount of code required for JPA as a Data access solution through jPA-based Repository.

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

The preparatory work

  • IDEA
  • JDK1.8
  • SpringBoot 2.1.3

The pom.xml file introduces the following dependencies:

<?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 - the SNAPSHOT</version>
    <name>jpa</name>
    <description>jpa Demo project for Spring Boot</description>

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

    <dependencies>

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

        <! Mysql > connect to mysql
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <! -- Lombok dependency -->
        <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>
Copy the code

Briefly, add JPA dependencies; The mysql connection class is used to connect data; Web startup class, but all Web applications need to rely on it; Lombok is used to simplify entity classes. Won’t see this old article introduced: SpringBoot combat (3) | use LomBok

Application. Yaml configuration file

spring:
# database related
  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 related
  jpa:
    hibernate:
      ddl-auto: update   #ddl-auto: set to create to re-create the table each time
    show-sql: true
Copy the code

The repository (dao) layers

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 purpose of this class <br/> *@author <a href="[email protected]">nasus</a><br/>
 */
@Repository
public interface StudentRepository extends JpaRepository<Student.Integer>, CrudRepository<Student.Integer> {}Copy the code

Can be seen from the above, JpaRepository PangingAndSortingRepository inheritance in CrudRepository inheritance.

Provide basic add and delete CrudRepository PagingAndSortingRepository provide paging and sorting method; JpaRepository provides the methods needed by JPA. You can select the interface to inherit according to your needs.

The benefits of using these interfaces are:

  1. Inheriting these interfaces enables Spring to find custom database operation interfaces and generate proxy classes that can later be injected into the Spring container.
  2. The associated SQL operations can be generated by proxy classes without being written

The service layer

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 purpose of this class <br/> *@author <a href="[email protected]">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(a);
}
Copy the code

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 purpose of this class <br/> *@author <a href="[email protected]">nasus</a><br/>
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

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

    /** * Query 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(a) {
        returnstudentRepository.findAll(); }}Copy the code

The Controller layer builds restful apis

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 purpose of this class <br/> *@author <a href="[email protected]">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(a){
        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); }}Copy the code

The test results

Other interfaces have passed the Postman test without problems.

Download the source code: github.com/turoDog/Dem…

After the language

Spring Data JPA is used by SpringBoot to access the Mysql database. Finally, if you are interested in Python and Java, please long press the QR code to follow the wave. I will try to bring you value. If you think this article is even a little help to you, please help to look good and let more people know.

In addition, after paying attention to send 1024 can receive free learning materials. Python, C++, Java, Linux, Go, front-end, algorithm sharing