使用Spring Boot和Gradle来使用Doma2

透过这篇文章能理解的内容

    Spring bootでGradleを利用してDomaを使うための方法

这篇文章没有提到的内容

    Domaの機能に対する説明

前提条件

在这篇文章中使用的各个版本。

    • JDK 8

 

    • Spring boot 1.3.5.RELEASE

 

    Gradle 2.13

增加依赖关系

在 build.gradle 文件的 dependencies 中添加所需的依赖关系。

compile('org.seasar.doma.boot:doma-spring-boot-starter:1.0.2')
compile('mysql:mysql-connector-java:5.1.38')

请根据使用的数据库进行适当更改,虽然连接器是MySQL。

此外,需要在编译之前将Doma处理的SQL文件复制到目标文件夹,因此在build.gradle中添加以下内容。

尝试使用SpringBoot+Doma2+Gradle

processResources.destinationDir = compileJava.destinationDir
compileJava.dependsOn processResources

结果是build.gradle如下所示。

// ・・・(省略)
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
    [compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

    processResources.destinationDir = compileJava.destinationDir
    compileJava.dependsOn processResources

    repositories {
        mavenCentral()
    }

    dependencies {
        // spring
        compile('org.springframework.boot:spring-boot-starter-actuator')
        compile('org.springframework.boot:spring-boot-actuator-docs')
        compile('org.springframework.boot:spring-boot-starter-aop')
        compile('org.springframework.boot:spring-boot-devtools')
        compile('org.springframework.boot:spring-boot-starter-mail')
        compile('org.springframework.boot:spring-boot-starter-security')
        compile('org.springframework.boot:spring-boot-starter-thymeleaf')
        compile('org.springframework.boot:spring-boot-starter-validation')
        compile('org.springframework.boot:spring-boot-starter-web')
        compile('org.springframework.boot:spring-boot-starter-websocket')

        // extension
        compile('org.projectlombok:lombok:1.16.6')

        // database
        compile('org.seasar.doma.boot:doma-spring-boot-starter:1.0.2')
        compile('mysql:mysql-connector-java:5.1.38')

        // specification
        testCompile('org.springframework.boot:spring-boot-starter-test')
    }
// ・・・(省略)

设置数据源的配置

由于我喜欢使用yaml格式,所以我会将它写在application.yml中。

# Spring Core
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/{dbname}
    username: {username}
    password: {password}

# Doma2 Reference URL <https://github.com/domaframework/doma-spring-boot>
doma:
  dialect: mysql
  sql-file-repository: no_cache

如果使用 MySQL,请根据环境设置括号中的值。如果使用其他数据库,请根据环境更改 driver-class-name、url 和 doma.dialect 等参数。关于 doma 的具体设置方法,请参考这里。

后续步骤

制作实体类,创建DAO接口,编写SQL,然后就可以使用了。查看GitHub的README就可以轻松理解。

在本文中,我写了一些在上述的README中没有提到的小事情,如果不做的话就无法进行协作。我可能会使用示例项目来修改本文,并且可能会写有关实体类和DAO接口的自动生成以及事务和日志输出等方面的内容。

bannerAds