jOOQ 代码生成工具的使用说明

文章目录

  • 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)如下:


<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-3.10.0.xsd">
  
  <jdbc>
    <driver>org.postgresql.Driverdriver>
    <url>jdbc:postgresql://localhost:5432/mydburl>
    <user>adminuser>
    <password>123456password>
  jdbc>

  <generator>
    <database>
      
      <name>org.jooq.util.postgres.PostgresDatabasename>

      
      <includes>.*includes>

      
      <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>publicinputSchema>
    database>

    <generate>
      
    generate>

    <target>
      
      <packageName>com.gnetna.dbpackageName>

      
      <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>

  
  
  <groupId>org.jooqgroupId>
  <artifactId>jooq-codegen-mavenartifactId>
  <version>3.11.10version>

  
  <executions>
    <execution>
      <goals>
        <goal>generategoal>
      goals>
    execution>
  executions>

  
  <dependencies>
    <dependency>
      <groupId>org.postgresqlgroupId>
      <artifactId>postgresqlartifactId>
      <version>9.4.1212version>
    dependency>
  dependencies>

  
  <configuration>

    
    <jdbc>
      <driver>org.postgresql.Driverdriver>
      <url>jdbc:postgresql:postgresurl>
      <user>postgresuser>
      <password>testpassword>
    jdbc>

    
    <generator>
      <database>
        <name>org.jooq.meta.postgres.PostgresDatabasename>
        <includes>.*includes>
        <excludes>excludes>
        
        <inputSchema>publicinputSchema>
      database>
      <target>
        <packageName>org.jooq.codegen.maven.examplepackageName>
        <directory>target/generated-sources/jooqdirectory>
      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


<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-3.10.0.xsd">
  <generator>
    <database>
      <name>org.jooq.util.ddl.DDLDatabasename>
      <properties>
            <property>
              <key>scriptskey>
              <value>F:/jooq/schema.sqlvalue>
            property>
            <property>
              <key>sortkey>
              <value>semanticvalue>
            property>
      properties>
    database>

    <target>
      <packageName>com.gnetnapackageName>
      <directory>./directory>
    target>
  generator>
configuration>

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
jOOQ 代码生成工具的使用说明_第1张图片

3、查看生成的 代码
jOOQ 代码生成工具的使用说明_第2张图片

示例

jooq-config.xml


<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-3.10.0.xsd">

<jdbc>
    <driver>org.postgresql.Driverdriver>
    <url>jdbc:postgresql://gnetna.com:5432/chorusdburl>
    <user>chorususer>
    <password>xxxxxxpassword>
jdbc>

<generator>
    <database>
        <name>org.jooq.util.postgres.PostgresDatabasename>

        <includeTables>trueincludeTables>
        <includeRoutines>falseincludeRoutines>
        <includePackages>falseincludePackages>
        <includePackageRoutines>falseincludePackageRoutines>
        <includePackageUDTs>falseincludePackageUDTs>
        <includePackageConstants>falseincludePackageConstants>
        <includeUDTs>falseincludeUDTs>
        <includeSequences>falseincludeSequences>
        <includePrimaryKeys>falseincludePrimaryKeys>
        <includeUniqueKeys>falseincludeUniqueKeys>
        <includeForeignKeys>falseincludeForeignKeys>
        <includeIndexes>falseincludeIndexes>
        <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>publicinputSchema>
    database>

    <generate>
        <daos>truedaos>
        
        
        
        
    generate>

    <target>
        <packageName>com.platform.choruspackageName>
        <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

你可能感兴趣的:(数据库)