Spring boot from scratch integrates spring data JPA to realize simple application

Keywords: Java Spring Hibernate MySQL Database

This paper introduces the simple application of spring boot integrating spring data JPA

What is spring data jpa? We can't help thinking about it. In fact, spring data jpa uses hibernate by default and spring data jpa technology, which implements the template Dao layer. It only needs to inherit an interface in Dao to easily complete "add, delete, modify and check, so the essence is the integration of springboot and hibernate. Why do you want spring data jpa with hibernate already!!! In fact, the developers of jpa and Hibernate are actually the same author... emmmm

Don't talk too much and start to implement!

1, Create a spring boot project and add related dependencies: (you can refer to my article to create a spring boot project

https://www.cnblogs.com/bgyb/p/12070279.html

      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--MySQL rely on-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
      <!--  spring-data-jpa rely on-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

II. Configuration application.yml Configure: (pay attention to the hierarchical relationship, hold down the Ctrl key, move to the top of the attribute, and the mouse button changes to the small hand shape, which is correct)

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/easybuy?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: update  #Start the application and automatically go to the database to help us create tables
    show-sql: true #Show sql

3, Create entity class (entity), data interface (mapper), interceptor (controller)

entity class:

import org.springframework.boot.autoconfigure.domain.EntityScan;

import javax.persistence.*;

//Using JPA annotations to configure mapping relationships
@Entity //Tell JPA that this is an entity class (a class mapped to a data table)
@Table(name="user") //@Table to specify which data table to correspond to; if the default table name is omitted, it is user
public class User {
    @Id //Represent primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY) //Set primary key
    private Integer id;

    @Column(name = "u_name") //This is a column corresponding to the data table. If the name is not specified in the annotation, the column name in the table is the same as the attribute name by default
    private String name;

    @Column(name = "u_email")
    private String email;

    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;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Data interface (mapper):

import com.poje.myspringjpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

//Inherit the JpaRepository to complete the operation on the database, specify the type of javabean, and its javabean primary key property type
public interface UserMapper extends JpaRepository<User,Integer> {

    //Method body can customize method for operation
    
}

Interceptor:

import com.poje.myspringjpa.entity.User;
import com.poje.myspringjpa.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class UserController {
    @Autowired
    UserMapper userMapper; //Inject mapper layer

    //According to the id query, query a single
    @RequestMapping("/hello/{id}")
    @ResponseBody
    public User hello(@PathVariable("id") Integer id){
       // User user =  userMapper.findOne(id); for spring boot2.0 and above, change findOne(id) to findById(id).get()
        User user = userMapper.findById(id).get(); //Query method of jpa
        return  user;
    }

    //Query all
    @RequestMapping("/findAll")
    @ResponseBody
    public List<User> findAll(){
        List<User> list =userMapper.findAll();//Query method of jpa
        return  list;
    }

}

4, After completing the above configuration, start the Springboot project:

From the console, we can see that spring data JPA helps us execute the CREATE TABLE statement. We can go to the database to check it...

As shown in the figure, the database table has been created successfully:

We create several pieces of data into the table, open the browser, and enter the url: http://localhost:8080/hello/2, you can see the result and the sql statement of the console.

 

 

The browser side effect is as follows:

 

 

 

So far, Springboot has integrated jpa to realize simple table creation and query! (add a chicken leg to yourself in the evening)

My message: write blog hope to record the present, learning is endless! Strive to be a clean stream in IT field!

Posted by k4pil on Fri, 22 May 2020 02:53:32 -0700