JOOQ学习笔记:gradle版代码生成、生成指定的数据库

环境

Java:1.8
jooq: 3.12.2
mysql: 8.0.15
电脑:MacBook Pro

前言

简单搭建一个jooq的项目。
根据官网文档来操作的,在按照jOOQ in 7 easy steps
但是执行到代码生成时,遇到了麻烦。

步骤

创建项目

创建gradle项目,根据Intellij IDEA上面点击下一步就可以了。

因为公司是gradle项目,所以就创建这种类型的项目了。

创建数据库

在本机上创建数据库,官网有提供,代码如下:

CREATE DATABASE `library`;

USE `library`;

CREATE TABLE `author` (
  `id` int NOT NULL,
  `first_name` varchar(255) DEFAULT NULL,
  `last_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

生成代码

我卡在这一步很久了,所以写这篇,记录下。

这个步骤的目的,就是为了让jooq,帮我们把数据模型和数据查询的基础代码都帮我生成好。

官网的第三步,方式很原始。用的是java命令来生成。我没试,因为实际项目不可能这样生成。

Code generation
这个链接,是官网专门讲解如何生成代码的。(方式有很多种)

因为我是gradle,所以我参考的是Running the code generator with Gradle
这里面讲了两种方式:
① 使用gradle官方的插件
② 使用xmlMarkupBuilder的方式

公司使用的是插件,我这里使用的是第二种。第二种的好处是不依赖第三方插件(但是现在的项目能不依赖第三方的很少)。

直接贴我自己的配置:

import groovy.xml.MarkupBuilder
import org.jooq.codegen.GenerationTool
apply plugin: 'java'
group 'com.misssad'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
    mavenCentral()
}
dependencies {
    compile("org.jooq:jooq:3.12.2")
    compile("org.jooq:jooq-meta:3.12.2")
    compile("org.jooq:jooq-codegen:3.12.2")
    compile('mysql:mysql-connector-java:8.0.15')

    testCompile("junit:junit:4.12")
}
buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath 'org.jooq:jooq-codegen:3.12.2'
        classpath('mysql:mysql-connector-java:8.0.15')
    }
}
task jooqCodeGenerate {
    def writer = new StringWriter()
    def xml = new MarkupBuilder(writer).configuration('xmlns': 'http://www.jooq.org/xsd/jooq-codegen-3.12.0.xsd'){
        jdbc() {
//            driver('com.mysql.jdbc.Driver')
            driver('com.mysql.cj.jdbc.Driver ')
            url('jdbc:mysql://localhost:3306/library?useSSL=false&useUnicode=true&characterEncoding=UTF-8')
            user('root')
            password('rootroot')
        }
        generator() {
            database() {}
            generate([:]) {
                pojos true
                daos true
            }
            target() {
                packageName('org.jooq.example.gradle.db')
                directory('src/main/java')
            }
        }
    }
    GenerationTool.generate(writer.toString())
}

和官网不同的地方:

官网
数据库H2MySQL
执行方式idea 右键Run./gradlew jooqCodeGenerate 或右键Run

执行方式,我自己写成了task形式,这样就可以使用命令的方式来执行。


上面的配置,会把MySQL数据库的所有数据库都生成代码。
比如我的MySQL为:
在这里插入图片描述

上面的配置生成出来的代码为:
仔细看下图的左边包名
在这里插入图片描述

只想生成指定的数据库

如果我们只想生成指定的数据库,比如我们示例中的library数据库。
那么我们需要添加如下配置:

generator(){
    name('org.jooq.codegen.JavaGenerator')
    // database是关键
    database(){
        name('org.jooq.meta.mysql.MySQLDatabase')
        inputSchema('library')
        includes('.*')
        excludes()
    }
    generate([:]) {
        pojos true//是否生成数据表对应的javabean类
        daos true//是否生成数据表对应的dao层,这里生成的dao能执行基本的增删改查sql操作,复杂一点的操作需要自己写dao
    }
    //生成类输出目录
    target() {
        packageName('com.study.jooq.data')//输出具体目录,生成的jooq类会在这个目录底下
        directory('src/main/java')//输出根目录
    }
}

说明:

generator中的name指定代码生成器;

generator层中name支持的语言
org.jooq.codegen.JavaGeneratorJava
org.jooq.codegen.ScalaGeneratorScala

databasename用来指定数据库的方言;
其格式如下:

org.jooq.meta.[database].[全大写database]Database

比如:
MySQL

org.jooq.meta.mysql.MYSQLDatabase

jooq总共支持的方言有:

org.jooq.meta.auroramysql.AuroraMySQLDatabase
org.jooq.meta.aurorapostgres.AuroraPostgresDatabase
org.jooq.meta.cubrid.CUBRIDDatabase
org.jooq.meta.db2.DB2Database
org.jooq.meta.derby.DerbyDatabase
org.jooq.meta.firebird.FirebirdDatabase
org.jooq.meta.h2.H2Database
org.jooq.meta.hana.HANADatabase
org.jooq.meta.hsqldb.HSQLDBDatabase
org.jooq.meta.informix.InformixDatabase
org.jooq.meta.ingres.IngresDatabase
org.jooq.meta.mariadb.MariaDBDatabase
org.jooq.meta.mysql.MySQLDatabase
org.jooq.meta.oracle.OracleDatabase
org.jooq.meta.postgres.PostgresDatabase
org.jooq.meta.redshift.RedshiftDatabase
org.jooq.meta.sqldatawarehouse.SQLDataWarehouseDatabase
org.jooq.meta.sqlite.SQLiteDatabase
org.jooq.meta.sqlserver.SQLServerDatabase
org.jooq.meta.sybase.SybaseDatabase
org.jooq.meta.teradata.TeradataDatabase
org.jooq.meta.vertica.VerticaDatabase

database中的inputSchema,这个就是指定生成哪个数据库的关键。
xml中的写法:

<inputSchema>[your database schema / owner / name]</inputSchema>

gradle中写法:

inputSchema('[your database schema / owner / name]')
eg:
inputSchema('library')

database中的includes用来指定包含哪些表的。即:哪些表可以生成出来了。
表达式为正则表达式,可以使用管道| 分割多个表达式;
XML写法:

<includes>.*</includes>

gradle写法:

includes('.*')

默认时匹配所有的。

database中的excludes用来排除哪些表的。可以使用管道分割多个表达式。
其比includes优先级高。
xml写法:

<excludes>
UNUSED_TABLE # This table (unqualified name) should not be generated
| PREFIX_.* # Objects with a given prefix should not be generated
| SECRET_SCHEMA\.SECRET_TABLE # This table (qualified name) should not be generated
| SECRET_ROUTINE # This routine (unqualified name) ...
</excludes>

翻译:

# 不会生成指定名称的表
# 包含PREFIX_前缀的不生成
# 不会生成指定名称的表
# SECRET_ROUTINE 这个名称的不生成

gradle写法:

excludes('UNUSED_TABLE |PREFIX_.*')

遇到的问题

SSL问题

WARN: Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45 , 5.6.26 and 5.7.6 requirements SSL connection must be established by default if explicit option isn’t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false’. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

因为我的MySQL版本为8,默认开启了SSL

解决办法:
添加useSSL=false

jdbc:mysql://localhost:3306/library?useSSL=false&useUnicode=true&characterEncoding=UTF-8

build.gradle

all buildscript {} blocks must appear before any plugins {} blocks in the script

按照上面的说法,所有的buildscript{}块,必须在plugins{}块之前。
然后我改成这样:

import groovy.xml.MarkupBuilder
import org.jooq.codegen.GenerationTool

group 'com.misssad'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
    mavenCentral()
}
dependencies {
    compile("org.jooq:jooq:3.12.2")
    compile("org.jooq:jooq-meta:3.12.2")
    compile("org.jooq:jooq-codegen:3.12.2")
    compile('mysql:mysql-connector-java:8.0.15')
    testCompile("junit:junit:4.12")
}
buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath 'org.jooq:jooq-codegen:3.12.2'
        classpath('mysql:mysql-connector-java:8.0.15')
    }
}
plugins {
    id 'java'
}
......

然后呢,报了下面这个错:

only buildscript {} and other plugins {} script blocks are allowed before plugins {} blocks, no other statements are allowed

这句话的意思就是说:只有buildscript{}块和其他plugins{}块,可以放在plugins{}块之前,其他都不行。

OK,我再改改,如下(正确版):

import groovy.xml.MarkupBuilder
import org.jooq.codegen.GenerationTool
buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath 'org.jooq:jooq-codegen:3.12.2'
        classpath('mysql:mysql-connector-java:8.0.15')
    }
}
plugins {
    id 'java'
}
group 'com.misssad'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
    mavenCentral()
}
......

这东西顺序很严格,我做了测试,即使是把:

group 'com.misssad'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8

放到plugins或者buildscript之前都不行,会报错。

驱动包

//            driver('com.mysql.jdbc.Driver')
            driver('com.mysql.cj.jdbc.Driver')

上面两个我都成功了,不过建议使用com.mysql.cj.jdbc.Driver

查看MySQL是否开启SSL

SHOW VARIABLES LIKE '%SSL%'

总结

目前只走了三个步骤。
生成代码这个步骤,有很多玩法,有待研究。

gradle方面知道这么一个结构:

plugins {
    // ...
}

dependencies {
    // ...
}

或者:

buildScript {
    // ...
}

plugins {
    // ...
}

repositories {
    // ...
}

就是有buildScript的情况下,一定要放在最前面

官网插件地址:
gradle-jooq-plugin

参考地址:

only build script and other plugins script blocks are allowed before plugins

记更新MySQL 8.0后踩过的那些坑

Running the code generator with Gradle

jOOQ in 7 easy steps

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山鬼谣me

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值