Be serious about writing, not clickbait.

The article is available at Github.com/niumoo/Java… And program ape Alang’s blog, point attention, don’t get lost.

preface

Springboot Data JPA and Spring JDBC belong to the Spring open source organization, after Spring JDBC and the development of the persistence layer framework, it is obvious that Spring Data JPA is more convenient and powerful than Spring JDBC, Otherwise there would be no need for development. Get started with Spring Data JPA with the following article.

1. Introduction to Spring Data JPA

Spring Data JPA is part of the Spring Data family that makes it easy to implement enhanced support for the data access layer, which for quite some time has been a hassle to implement for applications, requiring a lot of boilerplate code to perform simple queries or paging operations. The goal of Spring Data JPA is to improve the operation of the data access layer with minimal actual coding.

2. Spring Data JPA dependency

This experiment is based on the experiment code in Article 9 of the series. The configuration of the data source in the experiment code can also be referred to article 9 of the series. The Spring Data JPA section is only demonstrated here.

Create a Spring Boot project to introduce the required dependencies.

    <dependencies>
        <! -- Spring Boot Web Development integration -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>spring-boot-starter-json</artifactId>
                    <groupId>org.springframework.boot</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <! -- Ali Fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

        <! -- Lombok tools -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <! The springBoot file handler will be displayed when the springboot file is configured.
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <! -- Unit tests -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

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

        <! Add database link -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <! Druid = druid;
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
    </dependencies>
Copy the code

3. Spring Data JPA configuration

Configuration of the Druid data source is not explained anymore. See Article 9 of this series.

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# service startup port number
server.port=8080
spring.profiles.active=dev
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
spring.datasource.url=JDBC: mysql: / / 127.0.0.1:3306 / springboot? characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123
# Use druid data source
spring.datasource.type: com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize: 5
spring.datasource.minIdle: 5
spring.datasource.maxActive: 20
spring.datasource.maxWait: 60000
spring.datasource.timeBetweenEvictionRunsMillis: 60000
spring.datasource.minEvictableIdleTimeMillis: 300000
spring.datasource.validationQuery: SELECT 1 FROM DUAL
spring.datasource.testWhileIdle: true
spring.datasource.testOnBorrow: false
spring.datasource.testOnReturn: false
spring.datasource.poolPreparedStatements: true
spring.datasource.filters: stat
spring.datasource.maxPoolPreparedStatementPerConnectionSize: 20
spring.datasource.useGlobalDataSourceStat: true
spring.datasource.connectionProperties: druid.stat.mergeSql=true; druid.stat.slowSqlMillis=500
# SpringBoot JPA
spring.jpa.show-sql=true
# create create the table every time, update, if the table exists, do not rebuild
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQL55Dialect
Copy the code

Spring.jpa. show-sql=true Prints SQL statements. Spring.jpa.hibernate. DDL -auto=update Automatically creates a table based on Enity. Update means that the table will not be recreated if it exists.

4. Spring Data JPA coding

Springboot Data JPA is a complete implementation of ORM. Entity classes correspond to Data table relationships one by one, so entity classes are Data table structures. Spring.jpa.hibernate.ddl -auto=update automatically creates an Entity data table annotated by @Entity in the data table at JPA runtime. If the table already exists, it will not be created.

4.1. Data Entity classes

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;

/**
 * <p>
 *
 * @EntityJPA entities *@Data GET SET TOSTRING
 * @NoArgsConstructorNo parameter construction *@AllArgsConstructorFully parametric structure *@Author niujinpeng
 * @Date 2018/12/19 17:13
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "user")
public class User {

    /** * user ID **@IdThe primary key *@GeneratedValueAutoincrement primary key */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    /** * User name */
    @Column(name = "username", length = 32, nullable = false)
    @notnull (message = "username cannot be empty ")
    private String username;
    /** * Password */
    @Column(name = "password", length = 32, nullable = false)
    @notnull (message = "password cannot be empty ")
    private String password;
    /** * age */
    @Column(name = "age", length = 3)
    private Integer age;
    /** ** birthday */
    @DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
    private Date birthday;
    /** * skills */
    private String skills;
}
Copy the code

4.2. JPA operation interface

JPA operation interface only needs to inherit JpaRepository, JpaRepository encapsulation common methods, such as add, delete, change, search page, can be directly used, if you need to customize the query method, you can add the constructor method name. Add a method to query User information based on username and password.

package net.codingme.boot.domain.repository;

import net.codingme.boot.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * <p>
 *
 * @Author niujinpeng
 * @Date2019/1/11 14:26 * /
@Repository
public interface UserRepository extends JpaRepository<User.Integer> {
     /** * a custom method to query User information based on username and password */
    User findByUsernameAndPassword(String username, String password);
}
Copy the code

At this point, Jpa functionality is ready to be tested, but the Service layer and Controller are not covered here. We will write Springboot unit tests to test Jpa.

5. Spring Data JPA testing

The use of Springboot unit test method can be convenient to test Springboot project, do not understand Springboot unit test can refer to the official documentation, of course, you can also directly see the following example code. The following four test methods are prepared to test the four functions of query according to Id, paging query, update data, and query according to username and password.

package net.codingme.boot.domain.repository;

import net.codingme.boot.domain.User;
import org.junit.Assert;
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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Optional;

/** * unit test */
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository;

    /** * id query */
    @Test
    public void findByIdUserTest(a) {
        Optional<User> userOptional = userRepository.findById(1);
        User user = userOptional.orElseGet(null);
        System.out.println(user);
        Assert.assertNotNull(user);
    }

    /** ** ** /
    @Test
    public void findByPageTest(a) {
        PageRequest pageRequest = PageRequest.of(0.2);
        Page<User> userPage = userRepository.findAll(pageRequest);
        List<User> userList = userPage.getContent();
        userList.forEach((user) -> System.out.println(user));
        Assert.assertNotNull(userList);
    }

    /** * update */
    @Test
    public void updateUserTest(a) {
        Optional<User> userOptional = userRepository.findById(1);
        User user = userOptional.orElseThrow(() -> new RuntimeException("User information not retrieved"));
        System.out.println(user.getAge());
        ;
        user.setAge(user.getAge() + 1);
        User updateResult = userRepository.save(user);
        Assert.assertNotNull(updateResult);
    }

    /** * query */ based on Username and Password
    @Test
    public void findByUsernameAndPasswordTest(a) {
        User user = userRepository.findByUsernameAndPassword("Darcy"."123"); System.out.println(user); Assert.assertNotNull(user); }}Copy the code

First, see that all four methods pass.Paging queries find two pieces of data in the database.

Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.birthday as birthday3_0_, user0_.password as password4_0_, user0_.skills as skills5_0_, user0_.username as username6_0_ from user user0_ limit ? Hibernate: select count(user0_.id) as col_0_0_ from user user0_ User(id=1, username=Darcy, password=123, age=18, Birthday =2019-01-12 21:02:31.0, skills=Go) User(id=3, username=Chris, password=456, age=23, Birthday = 2019-01-01 00:11:22. 0, skills = Java)Copy the code

There is no problem with querying by Id.

Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.birthday as birthday3_0_0_, user0_.password as password4_0_0_, user0_.skills as skills5_0_0_, user0_.username as username6_0_0_ from user user0_ where user0_.id=?
User(id=1, username=Darcy, password=123, age=18, birthday=2019-01-12 21:02:30.0, skills=Go)
Copy the code

The update operation also outputs THE SQL normally, without any exceptions.

Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.birthday as birthday3_0_0_, user0_.password as password4_0_0_, user0_.skills as skills5_0_0_, user0_.username as username6_0_0_ from user user0_ where user0_.id=? 18 Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.birthday as birthday3_0_0_, user0_.password as password4_0_0_, user0_.skills as skills5_0_0_, user0_.username as username6_0_0_ from user user0_ where user0_.id=? Hibernate: update user set age=? , birthday=? , password=? , skills=? , username=? where id=?Copy the code

The last one is the custom query operation. In the output of the above three methods, the age of Darcy user is 18, which should become 19 after updating and adding 1. The following is the result of the custom query.

Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.birthday as birthday3_0_, user0_.password as password4_0_, user0_.skills as skills5_0_, user0_.username as username6_0_ from user user0_ where user0_.username=? and user0_.password=?
User(id=1, username=Darcy, password=123, age=19, birthday=2019-01-12 21:02:30.0, skills=Go)
Copy the code

So there’s no problem. The article code has been uploaded to GitHub. The test code uses some JDK8 features, such as the use of Optional classes. I will write a separate part of the article about new JDK features in the future.

After < >

Hello world 🙂

I am a lang, lang of the moon, a technical tool person who moves bricks every day. Personal website: www.wdbyte.com If you want to subscribe, you can follow the public account of “Procedural Ape Alang”, or the blog of procedural ape Alang, or add me on wechat (WN8398).

This article has also been compiled at GitHub.com/niumoo/Java… Welcome Star.