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

1、简介

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

2、环境

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

3、步骤

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

        

  2)建立项目,修改pom中依赖为 springboot 1.5.9.RELEASE(这个是我经常使用版本,可修改)、添加druid数据库链接池,spring boot是经过各类starter+AutoConfiguration帮咱们简化配置。github

  

    <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接口,测试类,配置文件。web

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

         

 

  

 

    

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

                          

4、总结

   经过springDataJPA让咱们感觉到了开发DAO层的方便,有兴趣的话能够研究一些复杂用法,以前咱们一般使用重SQL模式,不少业务逻辑都放在了一条SQL中去帮咱们实现,遇到复杂SQL调优起来就会变的很麻烦,经过JPA咱们能够尝试一下轻SQL重JAVA代码的形式。数据库

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

相关文章
相关标签/搜索