Spring Boot 与 Kotlin使用Spring-data-jpa简化数据访问层


声明:本文转载自https://my.oschina.net/quanke/blog/1611469,转载目的在于传递更多信息,仅供学习交流之用。如有侵权行为,请联系我,我会及时删除。

在《Spring Boot 与 Kotlin 使用JdbcTemplate连接MySQL》 中介绍了一种基本的数据访问方式,结合构建RESTful API和使用Thymeleaf模板引擎渲染Web视图的内容就已经可以完成App服务端和Web站点的开发任务了。

然而,在实际开发过程中,对数据库的操作无非就“增删改查”。就最为普遍的单表操作而言,除了表和字段不同外,语句都是类似的,开发人员需要写大量类似而枯燥的语句来完成业务逻辑。

为了解决这些大量枯燥的数据操作语句,我们第一个想到的是使用ORM框架,比如:Hibernate。通过整合Hibernate之后,我们以操作Java实体的方式最终将数据改变映射到数据库表中。

为了解决抽象各个Java实体基本的“增删改查”操作,我们通常会以泛型的方式封装一个模板Dao来进行抽象简化,但是这样依然不是很方便,我们需要针对每个实体编写一个继承自泛型模板Dao的接口,再编写该接口的实现。虽然一些基础的数据访问已经可以得到很好的复用,但是在代码结构上针对每个实体都会有一堆Dao的接口和实现。

由于模板Dao的实现,使得这些具体实体的Dao层已经变的非常“薄”,有一些具体实体的Dao实现可能完全就是对模板Dao的简单代理,并且往往这样的实现类可能会出现在很多实体上。Spring-data-jpa的出现正可以让这样一个已经很“薄”的数据访问层变成只是一层接口的编写方式。比如,下面的例子:

import name.quanke.kotlin.chaper11_6_2.entity.User import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.query.Param   /**  * Created by http://quanke.name on 2018/1/10.  */  interface UserRepository : JpaRepository<User, Long> {      fun findByUsername(username: String): List<User>          @Query("from User u where u.username=:username")     fun findUser(@Param("username") username: String): User  } 

只需要通过编写一个继承自JpaRepository的接口就能完成数据访问,下面以一个具体实例来体验Spring-data-jpa给我们带来的强大功能。

由于Spring-data-jpa依赖于Hibernate。如果您对Hibernate有一定了解,下面内容可以毫不费力的看懂并上手使用Spring-data-jpa。如果您还是Hibernate新手,您可以先按如下方式入门,再建议回头学习一下Hibernate以帮助这部分的理解和进一步使用。

工程配置

build.gradle中添加相关依赖,加入以下内容:

compile "org.springframework.boot:spring-boot-starter-data-jpa:$spring_boot_version" 

如果使用jpa必须增加kotlin-jpa插件

和kotlin-spring插件一样,kotlin-jpa是一个包含在no-arg之上的插件。 该插件自动指定@Entity,@Embeddable和@MappedSuperclass no-arg注释。

buildscript {     dependencies {         classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"     } }  apply plugin: "kotlin-jpa" 

如果使用的 Gradle plugins DSL

plugins {   id "org.jetbrains.kotlin.plugin.jpa" version "1.2.20" } 

完整的build.gradle

group 'name.quanke.kotlin' version '1.0-SNAPSHOT'  buildscript {     ext.kotlin_version = '1.2.10'     ext.spring_boot_version = '1.5.4.RELEASE'     ext.springfox_swagger2_version = '2.7.0'     ext.mysql_version = '5.1.21'     repositories {         mavenCentral()     }     dependencies {         classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"         classpath("org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version")  //        Kotlin整合SpringBoot的默认无参构造函数,默认把所有的类设置open类插件         classpath("org.jetbrains.kotlin:kotlin-noarg:$kotlin_version")         classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version")     } }  apply plugin: 'kotlin' apply plugin: "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin apply plugin: 'org.springframework.boot' apply plugin: "kotlin-jpa"  //https://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell jar {     baseName = 'chapter11-6-2-service'     version = '0.1.0' } repositories {     mavenCentral() }   dependencies {     compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"     compile("org.jetbrains.kotlin:kotlin-reflect:${kotlin_version}")       compile "org.springframework.boot:spring-boot-starter-web:$spring_boot_version"     compile "org.springframework.boot:spring-boot-starter-data-jpa:$spring_boot_version"     compile "mysql:mysql-connector-java:$mysql_version"      testCompile "org.springframework.boot:spring-boot-starter-test:$spring_boot_version"     testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"  }  compileKotlin {     kotlinOptions.jvmTarget = "1.8" } compileTestKotlin {     kotlinOptions.jvmTarget = "1.8" } 

application.yml中配置:数据库连接信息(如使用嵌入式数据库则不需要)、自动创建表结构的设置,例如使用mysql的情况如下:

spring:   datasource:     url: jdbc:mysql://localhost:3306/test     username: root     password: 123456     driver-class-name: com.mysql.jdbc.Driver 

spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置属性,其主要作用是:自动创建、更新、验证数据库表结构。该参数的几种配置如下:

  • create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
  • create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
  • update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
  • validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。 至此已经完成基础配置,如果您有在Spring下整合使用过它的话,相信你已经感受到Spring Boot的便利之处:JPA的传统配置在persistence.xml文件中,但是这里我们不需要。当然,最好在构建项目时候按照之前提过的最佳实践的工程结构来组织,这样以确保各种配置都能被框架扫描到。

创建实体

创建一个User实体,包含id(主键)、username(姓名)、password(密码)属性,通过ORM框架其会被映射到数据库表中,由于配置了hibernate.hbm2ddl.auto,在应用启动的时候框架会自动去数据库中创建对应的表。

import javax.persistence.*  /**  * Created by http://quanke.name on 2018/1/10.  */  @Entity data class User(         @Id         @GeneratedValue(strategy = GenerationType.AUTO)         var id: Long = -1,         @Column(nullable = false)         var username: String = "",          var password: String = "" ) 

创建数据访问接口

下面针对User实体创建对应的Repository接口实现对该实体的数据访问,如下代码:

 import name.quanke.kotlin.chaper11_6_2.entity.User import org.springframework.data.jpa.repository.JpaRepository import org.springframework.data.jpa.repository.Query import org.springframework.data.repository.query.Param   /**  * Created by http://quanke.name on 2018/1/10.  */  interface UserRepository : JpaRepository<User, Long> {      fun findByUsername(username: String): List<User>      fun findByUsernameAndPassword(username: String, password: String?): User      @Query("from User u where u.username=:username")     fun findUser(@Param("username") username: String): User  } 

在Spring-data-jpa中,只需要编写类似上面这样的接口就可实现数据访问。不再像我们以往编写了接口时候还需要自己编写接口实现类,直接减少了我们的文件清单。

下面对上面的UserRepository做一些解释,该接口继承自JpaRepository,通过查看JpaRepository接口的API文档,可以看到该接口本身已经实现了创建(save)、更新(save)、删除(delete)、查询(findAll、findOne)等基本操作的函数,因此对于这些基础操作的数据访问就不需要开发者再自己定义。

在我们实际开发中,JpaRepository接口定义的接口往往还不够或者性能不够优化,我们需要进一步实现更复杂一些的查询或操作。由于本文重点在spring boot中整合spring-data-jpa,在这里先抛砖引玉简单介绍一下spring-data-jpa中让我们兴奋的功能,后续再单独开篇讲一下spring-data-jpa中的常见使用。

在上例中,我们可以看到下面两个函数:

  • fun findByName(name:String ):User
  • fun findByNameAndAge(name:String , age:Int ):User

它们分别实现了按name查询User实体和按name和age查询User实体,可以看到我们这里没有任何类SQL语句就完成了两个条件查询方法。这就是Spring-data-jpa的一大特性:通过解析方法名创建查询。

除了通过解析方法名来创建查询外,它也提供通过使用@Query 注解来创建查询,您只需要编写JPQL语句,并通过类似“:name”来映射@Param指定的参数,就像例子中的第三个findUser函数一样。

Spring-data-jpa的能力远不止本文提到的这些,由于本文主要以整合介绍为主,对于Spring-data-jpa的使用只是介绍了常见的使用方式。诸如@Modifying操作、分页排序、原生SQL支持以及与Spring MVC的结合使用等等内容就不在本文中详细展开,这里先挖个坑,后续再补文章填坑,如您对这些感兴趣可以关注我博客或简书,同样欢迎大家留言交流想法。

单元测试

在完成了上面的数据访问接口之后,按照惯例就是编写对应的单元测试来验证编写的内容是否正确。这里就不多做介绍,主要通过数据操作和查询来反复验证操作的正确性。

 import name.quanke.kotlin.chaper11_6_2.entity.User import name.quanke.kotlin.chaper11_6_2.repository.UserRepository import org.apache.commons.logging.LogFactory 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.test.context.junit4.SpringRunner  /**  * Created by http://quanke.name on 2018/1/9.  */ @RunWith(SpringRunner::class) @SpringBootTest class ApplicationTests {      val log = LogFactory.getLog(ApplicationTests::class.java)!!      @Autowired     lateinit var userRepository: UserRepository      @Test     fun `jpa test"`() {  //        val username = "quanke" //        val password = "123456"          val user = User()          user.username = "quanke.name"         user.password = "12"         userRepository.save(user)          log.info("总共用户: ${userRepository.count()}")          log.info("名字为quanke的用户: ${userRepository.findByUsername("quanke.name")}")       }  

更多Spring Boot 和 kotlin相关内容

欢迎关注《Spring Boot 与 kotlin 实战》

参考

全科龙婷

本文发表于2018年01月23日 08:50
(c)注:本文转载自https://my.oschina.net/quanke/blog/1611469,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如有侵权行为,请联系我们,我们会及时删除.

阅读 1685 讨论 1 喜欢 0

抢先体验

扫码体验
趣味小程序
文字表情生成器

闪念胶囊

你要过得好哇,这样我才能恨你啊,你要是过得不好,我都不知道该恨你还是拥抱你啊。

直抵黄龙府,与诸君痛饮尔。

那时陪伴我的人啊,你们如今在何方。

不出意外的话,我们再也不会见了,祝你前程似锦。

这世界真好,吃野东西也要留出这条命来看看

快捷链接
网站地图
提交友链
Copyright © 2016 - 2021 Cion.
All Rights Reserved.
京ICP备2021004668号-1