第二章-spring boot springDataJPA快速开发DAO层,junit测试

一、简介

  第一章介绍了spring boot简单入门,这一章介绍一下如何通过springDataJPA快速实现DAO层开发。

二、环境

  1. jdk1.8
  2. springboot 1.5.9.RELEASE
  3. apache maven(3.5.0)
  4. 开发工具(IntelliJ IDEA )

三、步骤

  1)通过idea file->new project->Spring Initializr 创建项目,选中web->web,sql->JPA、MySQL。

        

  2)创建项目,修改pom中依赖为 springboot 1.5.9.RELEASE(这个是我常用版本,可修改)、添加druid数据库连接池,spring boot是通过各种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)实体类、JPA接口,测试类,配置文件。

  注意需要给一个默认的构造方法

         

  

    

    通过这个测试案例,我们简单模拟了JPA的增、删、改、查功能,然后关联查询、指定字段查询也是支持的,这里不做过多介绍,需要打印sql时在配置文件中开启showsql属性为true即可,下图为运行结果。

                          

四、总结

   通过springDataJPA让我们感受到了开发DAO层的方便,有兴趣的话可以研究一些复杂用法,之前我们通常使用重SQL模式,很多业务逻辑都放在了一条SQL中去帮我们实现,遇到复杂SQL调优起来就会变的很麻烦,通过JPA我们可以尝试一下轻SQL重JAVA代码的形式。

   源码地址   https://github.com/binary-vi/binary.github.io/tree/master/SpringBoot-demo/demo02  

猜你喜欢

转载自www.cnblogs.com/vi-2525/p/8952256.html