Chapter 2 - spring boot springDataJPA rapid development of DAO layer, junit test

1. Introduction

  The first chapter introduces a simple introduction to spring boot. This chapter introduces how to quickly implement DAO layer development through springDataJPA.

2. Environment

  1. jdk1.8
  2. springboot 1.5.9.RELEASE
  3. apache maven (3.5.0)
  4. development tools (IntelliJ IDEA)

3. Steps

  1) Create a project through idea file->new project->Spring Initializr, select web->web, sql->JPA, MySQL.

        

  2) Create a project, modify the dependency in the pom to springboot 1.5.9.RELEASE (this is my common version and can be modified), add a druid database connection pool, and spring boot helps us simplify the configuration through various starter+AutoConfiguration.

  

    <dependencies>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.25</version>
        </dependency>

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

  3) Entity classes, JPA interfaces, test classes, configuration files.

  Note that you need to give a default constructor

         

 

  

 

    

    Through this test case, we simply simulated the functions of adding, deleting, modifying, and checking JPA, and then associated queries and specified field queries are also supported. I won't introduce too much here. When printing sql, enable the showsql property in the configuration file as true, the following figure shows the running result.

                          

4. Summary

   Through springDataJPA, we feel the convenience of developing the DAO layer. If we are interested, we can study some complex usages. Before, we usually used the heavy SQL mode, and many business logics were put into a single SQL to help us realize it. When we encounter complex SQL tuning It will become very troublesome. Through JPA, we can try the form of light SQL and heavy JAVA code.

   Source address    https://github.com/binary-vi/binary.github.io/tree/master/SpringBoot-demo/demo02  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324887788&siteId=291194637
Recommended