preface

Only a bald head can be strong.

Welcome to our GitHub repository Star: github.com/ZhongFuChen…

I don’t know how much you know about SpringBoot and SpringData JPA, but if you have learned Spring and Hibernate, then SpringBoot and SpringData JPA can be used in a minute. I will not say the benefits of SpringBoot and SpringData JPA, I also made rough notes when learning, interested students can go to see

  • SpringBoot is that simple
  • SpringData JPA is that simple

I actually wrote a small Demo after learning SpringBoot and SpringData JPA, but never sent it out (lazy). Recently, I have to write a management module (CRUD) for my graduation project, and I have not written the relevant SpringBoot and SpringData JPA construction tutorial, so this article was born.

First, build the environment from scratch

This time I use the IDEA editor to build the SpringBoot and Spring Data JPA environment

First, when creating a new project in IDEA, select Spring Initializr and then next.

Then fill in some information for the project (which isn’t really important, just do it yourself) and click Next

Then WHEN I checked LomBok, I checked LomBok(the other ones were not checked, since we can configure them in poM files later). You can see that the SpringBoot version is 2.1.3.

  • Note: If you don’t know LomBok well, do a search. This is a very useful plugin that allows you to avoid writing tedious set/get methods. Remember: To use lomBok, you also need to install plug-ins under IDEA

IDEA will then help us create a Maven-managed SpringBoot project. In this case, we will specify our own Maven download and rewrite its settings.xml file

Maven then downloads dependencies and necessary plugins (I’ve been waiting for about 10 minutes, when I can have a Java drink. Haha), and when it’s done, Our project now looks like this:

2. Improve POM documents

Now poM files only have SpringBoot and LomBok dependencies. To complete CURD functionality, we need to use the Spring Web module, Spring Data JPA, and MySQL driver dependencies, so we need to add these dependencies to poM files:


<! --Web necessary -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<! MySQL -- Java driver -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

Copy the code

The complete dependency diagram for poM files is as follows:

3. Configure the YML file

Now that we are using SpringData JPA and MySQL, we need to configure the most basic information for them. For example, the username and password of the database, the corresponding library, and the policy of SpringData JAP.


Server container configuration
server:
  port: 8887


# database configuration
spring:
  datasource:
    username: Fill in your own
    password: Fill in your own
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: JDBC :mysql:// Fill in your own machine :3306/ fill in your own library? useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    # JPA configuration
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

    # formatSQL should be written like this
    properties:
      hibernate:
        format_sql: true
Copy the code

The complete picture of YML file is as follows:

Database information to fill in their own on the line.

Write a User entity

My graduation design includes the management of users. Our user entity design is as follows (of course, yours can be different from mine, I’m just an example) :

package com.zhongfucheng.example.demo.domain;

import lombok.Data;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;

/** * Store user information **@author ozc
 * @version1.0 * /
@Entity // JPA annotations need to be added
@Table(name = "table_user") // Specify the name of the database table
@Data // lombok 
public class User implements Serializable {
    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String userId;

    private String userNickname;

    private String userPassword;

    private String userEmail;

    private Integer actiState;

    // Activation success and activation failure constants
    public static final int ACTIVATION_SUCCESSFUL = 1;
    public static final int ACTIVATION_UNSUCCESSFUL = 0;

    private String actiCode;

    private Date tokenExptime;

}
Copy the code

One more note: Since we have LomBok’s Data annotations and LomBok plug-ins already in IDEA, we don’t need to write set and get methods.

The User entity diagram is as follows:

Write a UserRepository

UserRepository is a dao layer, equivalent to UserDao/UserMapper, but called differently. For example, Struts2 prefers xxxAction, while SpringMVC prefers xxxxController.

In general, we inherit UserRepository from JpaRepository with the corresponding add, delete, alter, and query methods:


import com.zhongfucheng.example.demo.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;


/** * UserDao operates on the database *@author ozc
 * @version1.0 * /
public interface UserRepository extends JpaRepository<User.String> {}Copy the code

The UserRepository diagram looks like this:



,>
,>
,>

Write a UserService

Mysql > select * from user where user = ‘user’;


/ / interface
public interface UserService {

    List<User> getAllUser(a);
}

/ / implementation
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<User> getAllUser(a) {
        returnuserRepository.findAll(); }}Copy the code

The UserService diagram is as follows:

Why is there a findAll() method? Because our UserRepository inherits JpaRepository

Write a UserController

The UserController calls the service method to see if it returns success. If it does, our environment is ok.

The UserController code is as follows:


@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /** * get all users */
    @GetMapping(value = "/user", produces = {"application/json; charset=UTF-8"})
    public void  getAllUser (a) {

        List<User> allUser = userService.getAllUser();

        for(User user : allUser) { System.out.println(user); }}}Copy the code

The Controller code is shown as follows:

Eight, test to see if you can return data

Go to DemoApplication, right click, and start our SpringBoot project:

In the browser to enter our url: http://localhost:8887/user. Then we view from the background, print out the query SQL statement, has been background has been printed table records.

The last

We can find a way to use SpringBoot+SpringData JPA that doesn’t require a lot of configuration and doesn’t require a lot of code to look up data from the database. Perfect for us to do some simple tests and small functions. If you are not familiar with SpringData JPA, please go to the relevant tutorial. I believe you can get started soon.

Happy to export dry Java technology public number: Java3y. There are more than 200 original technical articles, massive video resources, beautiful brain map, might as well pay attention to it!

Think my article is written well, might as well click a thumbs-up!