There is the concept of flying in the sky, there must be the realization of landing

  • The concept ten times is not as good as the code once, my friend, I hope you can type all the code cases in the article once

  • Like it before you look at it, make it a habit

SpringBoot illustrated tutorial series article directory

  1. SpringBoot图文教程1 “concept + case mind mapping” “basics”
  2. Use “logback” and “log4j” to log.
  3. SpringBoot graphic tutorial 3 – “‘ first love ‘complex” integrated Jsp
  4. 4 – SpringBoot implementation file upload and download
  5. Use Aop in SpringBoot
  6. SpringBoot Tutorial 6 – The use of filters in SpringBoot
  7. SpringBoot tutorial 7 – The use of SpringBoot interceptor posture is available here
  8. SpringBoot integration with MBG code Generator
  9. SpringBoot import/export Excel “Apache Poi”
  10. SpringBoot graphic tutorials 10 – template export Excel export | | millions data image export “easypoi”
  11. SpringBoot integration with MybatisPlus

preface

In the previous article, a series of Mybatis related technologies such as Mybatis, MBG and MybatisPlus were introduced. Some friends mentioned Jpa in the comment section, and also commented on the advantages and disadvantages of SpringData Jpa and Mybatis. However, whether convenient or powerful, each technology has its own use scenarios, so I will not discuss the good or bad, today brings the use of Jpa tutorial, each technology according to your needs.

What is SpringData Jpa

SpringData profile

SpringData is an official default database access technology used by SpringBoot, which simplifies access operations to various databases, including but not limited to Mysql, Redis, and MongoDB.

IO /projects/sp… It can be seen from the official website that SpringData can operate many technologies, in addition to Mysql, Redis, MongoDB, es, Hadoop and so on

So how does SpringData simplify access?

In SpringData, a unified set of interfaces is provided to implement operations on the data access layer, namely the Repository interface. Basic CRUD, query, sort, and paging operations are provided in the interface.

The main API of SpringData:

  • Repository: Unified interface
  • RevisionRepository> : Based on optimistic locking
  • CrudRepository: Basic CRUD operation
  • PagingAndSortingRepository: basic CRUD and paging

Simply put, as long as you import SpringData’s dependencies, you don’t need any methods to perform basic data operations directly, because those methods are written in the interface.

But wait!! There seems to be something wrong

Having an interface is one thing, but if you don’t have an implementation or can’t use it, where is the implementation of SpringData?

If you want to implement the method, look for the protagonist of the day, SpringData Jpa.

SpringData Jpa

As shown in the figure, for our Java program to access the database, we only need to call the unified API method of SpringData. As for how to complete the task after calling the method, we do not need to worry. SpringData has many implementations for different technologies, such as: SpringData Redis, SpringData Jpa, SpringData MongoDB, etc. SpringData Jpa is the implementation of relational databases.

Jpa, Java Persistence Api, is a set of Java EE platform standard ORM specification, through JPA can achieve access to relational databases. In Jpa, there is JpaRepository interface, and the authoring interface inherits JpaRepository with cruD and paging functions.

As shown in the figure, Jpa can integrate many technologies, Hibernate, Toplink, OpenJpa, and the default implementation of SpringData Jpa is Hibernate.

To put it simply: SpringData Jpa implements SpringData, and Hibernate implements SpringData Jpa. So it’s really Hibernate that does the work in the end.

Basic use of Jpa in SpringBoot

Basic steps:

  1. Create project import dependencies
  2. Write entity classes to add Jpa annotations to configure mappings
  3. Write a Dao interface to manipulate a Repository for entity classes
  4. Configure Jpa
  5. Test class testing

1. Create a project import dependency configuration data source

Create project imports with the following dependencies:


       

<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 https://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.4. The RELEASE</version>

        <relativePath/> <! -- lookup parent from repository -->

    </parent>



    <groupId>com.lby</groupId>

    <artifactId>boot-jpa</artifactId>

    <version>0.0.1 - the SNAPSHOT</version>

    <name>boot-jpa</name>

    <description>Demo project for Spring Boot</description>



    <properties>

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

    </properties>



    <dependencies>

<! -- jpa-->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-jpa</artifactId>

        </dependency>

<! -- mysql-->

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

            <scope>runtime</scope>

        </dependency>



<! -- lombok-->

        <dependency>

            <groupId>org.projectlombok</groupId>

            <artifactId>lombok</artifactId>

            <version>1.18.4</version>

            <scope>provided</scope>

        </dependency>



<! - test - >

        <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

configuration

Note: Unlike Mybatis, you can not create a table in the boot of the configured database. Jpa will help you to create a database table according to the entity class if there is no table when you use Jpa to operate the database.

2. Write entity classes to add Jpa annotations to configure mappings

To manipulate data in a database through Jpa, you need to associate entity classes with the database

package com.lby.bootjpa.entity;





import lombok.Data;



import javax.persistence.*;



/ * *

 * @DataLombok annotations generate get sets and so on

 * 

* Annotations are used to configure mappings between entity classes and database tables

 * @EntityTell JPA that this is an entity class (a class that maps to a data table)

 * @TableConfigure which table the current entity class corresponds to. The default table name is admin

* /


@Data

@Entity

@Table(name = "admin")

public class Admin {

    / * *

     * @IdThat means this is the primary key

     * @GeneratedValuePrimary key generation rule IDENTITY increment

* /


    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Integer adminId;

    / * *

* Configure mappings between properties and database table fields

* name Indicates the field name of the database table

* /


    @Column(name = "username")

    private String username;

    @Column

    private String password;



}

Copy the code

3. Create a Dao interface to manipulate a Repository of entity classes.

/ * *

* JpaRepository The type of the primary key attribute of the entity class generic 2 that generic 1 operates on

* /


public interface AdminRepository extends JpaRepository<Admin.Integer{

}

Copy the code

4. Configure Jpa

spring:

    jpa:

      hibernate:

      As mentioned earlier, Jpa will create this configuration if there are no tables in the database

The table structure will be updated if the entity class changes

        ddl-auto: update

    Print information about executed SQL statements in logs

      show-sqltrue

Copy the code

5. Test class tests

With the basic configuration done, let’s simply test it with the test class

package com.lby.bootjpa;



import com.lby.bootjpa.entity.Admin;

import com.lby.bootjpa.repository.AdminRepository;

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.SpringRunner;



@RunWith(SpringRunner.class)

@SpringBootTest(classes = {BootJpaApplication.class})

public class BootJpaApplicationTests {

    @Autowired

    private AdminRepository adminRepository;



    @Test

    public void contextLoads(a) {

        Admin admin = new Admin();

        admin.setUsername("hhh");

        admin.setPassword("12345");

        adminRepository.save(admin);

    }







}

Copy the code

The test class runs as follows

conclusion

Tips: This article mainly explains the way to integrate SpringData Jpa in the SpringBoot project, about the use of SpringData Jpa is relatively basic, if you want to learn more comprehensive use of SpringData Jpa, please continue to pay attention to, will write a comprehensive use of Jpa tutorial.

Congratulations on completing this chapter. A round of applause! If this article is helpful to you, please help to like, comment, retweet, this is very important to the author, thank you.

Let’s review the learning objectives of this article again

  • Master the use of SpringData Jpa in SpringBoot

To learn more about SpringBoot, stay tuned for this series of tutorials.

Ask for attention, ask for likes, ask for retweets

Welcome to pay attention to my public account: Teacher Lu’s Java notes, will update Java technology graphic tutorials and video tutorials in the long term, Java learning experience, Java interview experience and Java actual combat development experience.