文章目录

  • 1、命令行工具生成代码
    • 1.1 下载 jar 包
    • 1.2 配置数据源
    • 1.3 执行命令
    • 1.4 数据访问
  • 2、Maven 插件
  • 3、DDL
  • 示例

1、命令行工具生成代码

1.1 下载 jar 包

代码生成是开源免费的,需要4个 jar 包,从 Maven Central 下载:

  • jooq-3.10.8.jar : 核心包,需要在项目中引用;
  • jooq-meta-3.10.8.jar : 模型解析包;
  • jooq-codegen-3.10.8.jar :生成数据库模型对应代码的工具包
  • postgresql-42.2.5.jar: 所需的 JDBC Driver

1.2 配置数据源

首先,在目标数据库中创建所需的数据表,例如:

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

这里以 PostgreSQL 为例,配置文件(jooq-config.xml)如下:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-3.10.0.xsd"><!-- Configure the database connection here --><jdbc><driver>org.postgresql.Driver</driver><url>jdbc:postgresql://localhost:5432/mydb</url><user>admin</user><password>123456</password></jdbc><generator><database><!-- The database dialect from jooq-meta. Available dialects arenamed org.jooq.util.[database].[database]Database.Natively supported values are:org.jooq.util.ase.ASEDatabaseorg.jooq.util.cubrid.CUBRIDDatabaseorg.jooq.util.db2.DB2Databaseorg.jooq.util.derby.DerbyDatabaseorg.jooq.util.firebird.FirebirdDatabaseorg.jooq.util.h2.H2Databaseorg.jooq.util.hana.HANADatabaseorg.jooq.util.hsqldb.HSQLDBDatabaseorg.jooq.util.informix.InformixDatabaseorg.jooq.util.ingres.IngresDatabaseorg.jooq.util.mariadb.MariaDBDatabaseorg.jooq.util.mysql.MySQLDatabaseorg.jooq.util.oracle.OracleDatabaseorg.jooq.util.postgres.PostgresDatabaseorg.jooq.util.redshift.RedshiftDatabaseorg.jooq.util.sqlite.SQLiteDatabaseorg.jooq.util.sqlserver.SQLServerDatabaseorg.jooq.util.sybase.SybaseDatabaseThis value can be used to reverse-engineer generic JDBC DatabaseMetaData (e.g. for MS Access)org.jooq.util.jdbc.JDBCDatabaseThis value can be used to reverse-engineer standard jOOQ-meta XML formatsorg.jooq.util.xml.XMLDatabaseThis value can be used to reverse-engineer schemas defined by SQL files (requires jooq-meta-extensions dependency)org.jooq.util.ddl.DDLDatabaseThis value can be used to reverse-engineer schemas defined by JPA annotated entities (requires jooq-meta-extensions dependency)org.jooq.util.jpa.JPADatabaseYou can also provide your own org.jooq.util.Database implementationhere, if your database is currently not supported --><name>org.jooq.util.postgres.PostgresDatabase</name><!-- All elements that are generated from your schema (A Java regular expression.Use the pipe to separate several expressions) Watch out forcase-sensitivity. Depending on your database, this might beimportant!You can create case-insensitive regular expressions using this syntax: (?i:expr)Whitespace is ignored and comments are possible.--><includes>.*</includes><!-- All elements that are excluded from your schema (A Java regular expression.Use the pipe to separate several expressions). Excludes match beforeincludes, i.e. excludes have a higher priority --><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><!-- The schema that is used locally as a source for meta information.This could be your development schema or the production schema, etcThis cannot be combined with the schemata element.If left empty, jOOQ will generate all available schemata. See themanual's next section to learn how to generate several schemata --><inputSchema>public</inputSchema></database><generate><!-- Generation flags: See advanced configuration properties --></generate><target><!-- The destination package of your generated classes (within thedestination directory)jOOQ may append the schema name to this package if generating multiple schemas,e.g. org.jooq.your.packagename.schema1org.jooq.your.packagename.schema2 --><packageName>com.gnetna.db</packageName><!-- The destination directory of your generated classes --><directory>./</directory></target></generator>
</configuration>
  • inputSchema: 当根据数据库中的表来生成代码时,配置目标 schema,生成该 schema 下的所有表对应的代码,如果不填 public 将会生成很多垃圾代码,需要注意;

1、有几种 code genarator?

  • org.jooq.codegen.JavaGenarator
  • org.jooq.codegen.ScalaGenarator

可以创建自己的 genarator,定制代码风格。

2、genarator 的配置

  • jdbc:配置 driver,url,user,password
  • genarator:name, database, inputSchema

1.3 执行命令

将所需的 4 个 jar 包放置在特定路径下,执行命令:

java -cp jooq-3.10.8.jar;jooq-meta-3.10.8.jar;jooq-codegen-3.10.8.jar;postgresql-42.2.5.jar;. org.jooq.util.GenerationTool /jooq-config.xml

jOOQ 会从 classpath 中加载 jooq-config.xml 文件,如果没找到,就当前目录中查找。

1.4 数据访问

public static void main(String[] args) {String userName = "admin";String password = "123456";String url = "jdbc:postgresql://localhost:5432/mydb";try (Connection conn = DriverManager.getConnection(url, userName, password)) {DSLContext create = DSL.using(conn, SQLDialect.MYSQL);Result<Record> result = create.select().from(AUTHOR).fetch();for (Record r : result) {Integer id = r.getValue(AUTHOR.ID);String firstName = r.getValue(AUTHOR.FIRST_NAME);String lastName = r.getValue(AUTHOR.LAST_NAME);System.out.println("ID: " + id + " first name: " + firstName + " last name: " + lastName);}} catch (Exception e) {e.printStackTrace();}}

2、Maven 插件

使用 jOOQ-codegen-maven 插件生成代码:

<plugin><!-- Specify the maven code generator plugin --><!-- Use org.jooq            for the Open Source Editionorg.jooq.pro        for commercial editions, org.jooq.pro-java-6 for commercial editions with Java 6 support,org.jooq.trial      for the free trial edition Note: Only the Open Source Edition is hosted on Maven Central. Import the others manually from your distribution --><groupId>org.jooq</groupId><artifactId>jooq-codegen-maven</artifactId><version>3.11.10</version><!-- The plugin should hook into the generate goal --><executions><execution><goals><goal>generate</goal></goals></execution></executions><!-- Manage the plugin's dependency. In this example, we'll use a PostgreSQL database --><dependencies><dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><version>9.4.1212</version></dependency></dependencies><!-- Specify the plugin configuration.The configuration format is the same as for the standalone code generator --><configuration><!-- JDBC connection parameters --><jdbc><driver>org.postgresql.Driver</driver><url>jdbc:postgresql:postgres</url><user>postgres</user><password>test</password></jdbc><!-- Generator parameters --><generator><database><name>org.jooq.meta.postgres.PostgresDatabase</name><includes>.*</includes><excludes></excludes><!-- In case your database supports catalogs, e.g. SQL Server:<inputCatalog>public</inputCatalog>--><inputSchema>public</inputSchema></database><target><packageName>org.jooq.codegen.maven.example</packageName><directory>target/generated-sources/jooq</directory></target></generator></configuration>
</plugin>

Be sure, both jooq-3.11.10.jar and your generated package (see configuration) are located on your classpath. Once this is done, you can execute SQL statements with your generated classes.

3、DDL

http://www.jooq.org/doc/3.10/manual/code-generation/codegen-ddl/

多数情况,schema 都是通过 sql 脚本的形式定义,这种形式能方便 Flyway 等迁移工具的使用。如果项目中的 schema 完整的定义在 sql 文件中,那么 org.jooq.util.ddl.DDLDatabase 可能是更好的选择。

例如,schema.sql :

CREATE TABLE author (id INT NOT NULL,first_name VARCHAR(50),last_name VARCHAR(50) NOT NULL,date_of_birth DATE,year_of_birth INT,address VARCHAR(50),CONSTRAINT pk_t_author PRIMARY KEY (ID)
);

sql 文件中可以使用标准的 SQL,也可以使用数据库提供商扩展的 SQL。

配置 jooq-config.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-3.10.0.xsd"><generator><database><name>org.jooq.util.ddl.DDLDatabase</name><properties><property><key>scripts</key><value>F:/jooq/schema.sql</value></property><property><key>sort</key><value>semantic</value></property></properties></database><target><packageName>com.gnetna</packageName><directory>./</directory></target></generator>
</configuration>

备注:新版本中 DDLDatabase 的全路径为 org.jooq.meta.extensions.ddl.DDLDatabase

DDLDatabase 依赖 jooq-meta-extensions 模块,该模块属于非开源版本,在 Maven 上没有,需要自己构建。

具体操作步骤:

1、将所需的所有 jar 放在特定目录下,比如 F:\jooq

  • h2-1.4.199.jar
  • jooq-3.10.7.jar
  • jooq-codegen-3.10.7.jar
  • jooq-meta-3.10.7.jar
  • jooq-meta-extensions-3.10.7.jar
  • jooq-config.xml
  • schema.sql

2、执行命令:

java -cp jooq-3.10.7.jar;jooq-meta-3.10.7.jar;jooq-codegen-3.10.7.jar;jooq-meta-extensions-3.10.7.jar;h2-1.4.199.jar;. org.jooq.util.GenerationTool /config.xml

3、查看生成的 代码

示例

jooq-config.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-3.10.0.xsd">
<!-- Configure the database connection here -->
<jdbc><driver>org.postgresql.Driver</driver><url>jdbc:postgresql://gnetna.com:5432/chorusdb</url><user>chorus</user><password>xxxxxx</password>
</jdbc><generator><database><name>org.jooq.util.postgres.PostgresDatabase</name><includeTables>true</includeTables><includeRoutines>false</includeRoutines><includePackages>false</includePackages><includePackageRoutines>false</includePackageRoutines><includePackageUDTs>false</includePackageUDTs><includePackageConstants>false</includePackageConstants><includeUDTs>false</includeUDTs><includeSequences>false</includeSequences><includePrimaryKeys>false</includePrimaryKeys><includeUniqueKeys>false</includeUniqueKeys><includeForeignKeys>false</includeForeignKeys><includeIndexes>false</includeIndexes><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><inputSchema>public</inputSchema></database><generate><daos>true</daos><!--<jpaAnnotations>true</jpaAnnotations>--><!--<jpaVersion>2.2</jpaVersion>--><!--<validationAnnotations>true</validationAnnotations>--><!--<springAnnotations>true</springAnnotations>--></generate><target><packageName>com.platform.chorus</packageName><directory>./</directory></target>
</generator>
</configuration>

填写正确的数据库信息!

执行命令:

java -cp jooq-3.10.7.jar;jooq-meta-3.10.7.jar;jooq-codegen-3.10.7.jar;jooq-meta-extensions-3.10.7.jar;postgresql-42.2.5.jar;. org.jooq.util.GenerationTool /jooq-config.xml

jOOQ 代码生成工具的使用说明相关推荐

  1. 代码生成工具随笔(3)---占领最后一块黄金宝地

    目前代码生成工具多如繁星,绝大多数的代码生成工具都是基于数据库进行实体类.数据访问类.部分业务类等的代码生成,较少会用来生成易用.重用的界面代码,因为这块的逻辑很难控制,每个人的需求都不一样,而且把整 ...

  2. 支持自定义代码生成工具

    项目地址 https://github.com/kylin-hunter/k-commons/tree/main/k-code-generator 文章目录 项目地址 前言 一.架构 二.使用步骤 1 ...

  3. 狼奔代码生成工具使用心得

    狼奔代码生成工具(http://ltfwan.d33140.jit8.cn)是一款为程序员设计的代码生成器,更是一款软件项目智能开发平台,它可以自动生成ASP.NET页面及后台代码,采用了面向服务的架 ...

  4. 序列拼接工具Bowtie使用说明

    序列拼接工具Bowtie使用说明 2011-06-08 ~ ADMIN Bowtie是一个超级快速的,较为节省内存的短序列拼接至模板基因组的工具.它在拼接35碱基长度的序列时,可以达到每小时2.5亿次 ...

  5. benchmarksql测试mysql_数据库压力测试工具 -- BenchmarkSQL 使用说明

    关于数据库的压力测试,之前写过3篇Blog: 数据库基准测试(Database Benchmarking) 说明 数据库压力测试工具 -- Hammerdb 使用说明 数据库压力测试工具 -- Swi ...

  6. flutter图标按钮_Flutter开发第一个项目android studio 开发工具的使用说明

    Flutter开发第一个项目android studio 开发工具的使用说明 做个自我介绍 自我介绍还是有必要介绍一下的,毕竟这是网络里,你看不到我,我看不到你,只能通过文字来传递信息,本人做技术8年 ...

  7. 调整代码生成工具Database2Sharp的Winform界面生成,使其易于列表工具栏的使用。...

    在Winform界面开发的时候,有时候我们客户喜欢把功能放在列表界面的顶部,这样界面和功能整齐放置,也是一种比较美观的方式,基于这种方式的考虑,改造了代码生成工具的Winform界面生成规则,把增删改 ...

  8. CLR_via_C#.3rd 翻译[1.5 本地代码生成工具NGen.exe]

    1.5 The Native Code Generator Tool: NGen.exe 本地代码生成工具NGen.exe NGen.exe是和.NET框架绑定在一起的.当用户的机器上安装了一个应用程 ...

  9. 代码生成工具Database2Sharp功能功能完善及更新

    好久没有更新代码生成工具了,因为很多功能基本上能够应付日常的开发工作了,如C#代码生成.数据库文档导出.Sql脚本生成,但用户在使用过程中也发现了一些需要完善的地方,因此继续完善,以求更加实用方便. ...

最新文章

  1. unity中使用自定义shader进行光照贴图烘培无法出现透明度的坑爹问题
  2. SQL Server T-SQL高级查询
  3. jeesite3环境部署时初始化数据库注意问题
  4. LiveVideoStack线上分享第四季(三):在线教育的音视频架构设计及弱网对抗技术...
  5. html复选框值改变后事件,javascript – 从onclick/onchange事件获取HTML值的复选框
  6. Microsoft Visual Studio 打开代码出现乱码解决方案
  7. struts2中一些常用的写法 记录
  8. webpack3+node+react+babel实现热加载(hmr)
  9. 【MFC开发(6)】复选框按钮控件Check Box
  10. windows命令行测试硬盘速度
  11. 基于QT和DCMTK的Dicom 图像浏览器---目录
  12. HTML小游戏2—— 2048网页版(附完整源码)
  13. 使用screw一键生成数据库文档
  14. Unity 反转法线,在 Hierarchy 视图对象的快捷菜单中增加 Flip Mesh Normals(反转网格法线)项...
  15. CSS去除input框自带的叉号
  16. 对于Java毕业设计选题的一些看法
  17. SH7218T拆解手记(4)修改外屏大时钟
  18. 什么是 Power BI Desktop?
  19. c语言signed int与unsigned int的运算
  20. 队列实现杨辉三角(附详细图解)

热门文章

  1. nargchk和nargin
  2. DPDK入门(环境搭建以及小demo)
  3. 《卡耐基三部曲》(Yanlz+VR云游戏+Unity+SteamVR+云技术+5G+AI+人性的弱点+人性的优点+语言的突破+术业有专攻+世界观+人生观+价值观+志同道合+不卑不亢+立钻哥哥++==)
  4. 猿创征文 | Java知识【Java基础语法】
  5. 智能城市dqn算法交通信号灯调度_交通信号灯毕设论文(A).doc
  6. JODD与数据页面绑定
  7. 应对羊毛党的老手段不管用了,但有些公司依然有办法,他们是怎么做的?
  8. SPSS(二)SPSS实现多因素方差分析模型(图文教程+数据集)
  9. TSINGSEE车载视频监控技术在城市公交场景中的应用
  10. 笔记:腾讯云服务器的使用