JOOQ入門指南

JOOQ

JOOQ提供了SQLBuilder功能 ,數據遷移功能,SQL執行能力,執行生命週期的管理等屬性。相較hibernate,JOOQ執行SQL的過程對程序員的可見性更高。相較於mybatis SQL腳本的管理更爲靈活,在使用上減少了配置文件的管理和配置。

JOOQ的目標並不是成爲完整實現JPA協議的ORM框架,其更專注於SQL的執行,想要實現的是OLTP和大數據清洗場景下的數據管理.它並不是JAP框架的替代,相反,它更想成爲JPA協議框架的補充。

Whenever SQL is a good fit, jOOQ is a good fit. Whenever you’re operating and persisting the object graph, JPA is a good fit.And sometimes, it’s best to combine both。

代碼生成

type1:命令行生成

命令行如下:

 java -classpath jooq-3.13.2.jar;jooq-meta-3.13.2.jar;jooq-codegen-3.13.2.jar;reactive-    streams-1.0.2.jar;mysql-connector-java-8.0.20.jar;. org.jooq.codegen.GenerationTool /jooq.xml

在此之前需要準備1.java運行環境;2.執行命令行涉及的包;3.jooq.xml配置

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-3.13.0.xsd">
    <!-- 數據庫信息 -->
    <jdbc>
        <driver></driver>
        <url></url>
        <user></user>
        <password></password>
    </jdbc>

    <generator>
        <!-- The default code generator. You can override this one, to generate your own code style.
             Supported generators:
             - org.jooq.codegen.JavaGenerator
             - org.jooq.codegen.ScalaGenerator
             Defaults to org.jooq.codegen.JavaGenerator -->
        <name>org.jooq.codegen.JavaGenerator</name>

        <database>
            <!-- The database type. The format here is:
                 org.jooq.meta.[database].[database]Database -->
            <name>org.jooq.meta.mysql.MySQLDatabase</name>

            <!-- 需要生成代碼的數據庫Schema -->
            <inputSchema>jooq</inputSchema>

            <!-- All elements that are generated from your schema
                 (A Java regular expression. Use the pipe to separate several expressions)
                 Watch out for case-sensitivity. Depending on your database, this might be important! -->
            <includes>.*</includes>

            <!-- 聲明需要排除不生成java代碼的table-->
            <excludes></excludes>
        </database>
        <generate>
            <!--生成dao和pojo-->
            <daos>true</daos>
            <pojos>true</pojos>

            <!--把數據庫時間類型映射到java 8時間類型-->
            <javaTimeTypes>true</javaTimeTypes>
            <!--<interfaces>true</interfaces>-->
            <!--生成的代碼中添加spring註釋,比如@Repository-->
            <springAnnotations>true</springAnnotations>
            <pojosToString>true</pojosToString>
        </generate>
        <target>
            <!-- The destination package of your generated classes (within the destination directory) -->
            <packageName>包名</packageName>

            <!-- The destination directory of your generated classes. Using Maven directory layout here -->
            <directory>C:/workspace/MySQLTest/src/main/java</directory>
        </target>
    </generator>
</configuration>
type2:maven+springboot 生成
mvn clean install

需要準備1.java運行環境;2.執行命令行涉及的包;3.jooq.xml配置;4.maven 環境 ;5 包含jooq的相關依賴的

pom.xml

pom.xml如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.3.1.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.*.jooq</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

   <properties>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-jooq</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>runtime</scope>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <scope>runtime</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
         <exclusions>
            <exclusion>
               <groupId>org.junit.vintage</groupId>
               <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
         </exclusions>
      </dependency>
      <!-- https://mvnrepository.com/artifact/org.jooq/jooq-codegen-maven -->

   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
         <plugin>
            <groupId>org.jooq</groupId>
            <artifactId>jooq-codegen-maven</artifactId>
            <version>3.13.2</version>
            <executions>
               <execution>
                  <goals>
                     <goal>generate</goal>
                  </goals>
               </execution>
            </executions>
            <dependencies>
               <dependency>
                  <groupId>mysql</groupId>
                  <artifactId>mysql-connector-java</artifactId>
                  <version>8.0.20</version>
               </dependency>
            </dependencies>
            <configuration>
                <!--jooq 配置文件加載-->
               <configurationFile>src/main/resources/jooq.xml</configurationFile>
            </configuration>
         </plugin>
      </plugins>
   </build>

</project>

springboot 整合JOOQ

官方給出的方法爲在啓動配置中添加

#src\main\resources\application.properties 
spring.jooq.sql-dialect=H2

代碼生成器生成的dao不可直接使用,這是因爲生成的代碼中提供了兩個dao構造器,其中一個

import org.jooq.Configuration;
import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("authorDao")
public class AuthorDaoExt extends AuthorDao{
    @Autowired
    private DSLContext dsl;
    @Autowired
    public AuthorDaoExt(Configuration configuration) {
        super(configuration);
    }
//    @Autowired  當以這個構造器爲spring 託管時會導致springboot的dataSource配置無法生效
//    public AuthorDaoExt() {
//        super();
//    }
}

JOOQ可擴展組件:https://www.jooq.org/doc/3.14/manual/getting-started/use-cases/jooq-for-pros/

JOOQ作爲SQL構造器

import org.jooq.DSLContext;
import org.jooq.Query;
import org.jooq.SQLDialect;
import org.jooq.conf.ParamType;
import org.jooq.impl.DefaultDSLContext;
//靜態導入
import static org.jooq.impl.DSL.field;
import static org.jooq.impl.DSL.table;


public class JOOQBuilder {
    private static DSLContext create = new DefaultDSLContext(SQLDialect.MYSQL);

    public static void main(String[] args) {
        //將JOOQ做爲一個SQL構造器
        Query query = (Query)          create.select().from(table("AUTHOR")).where(field("AUTHOR.ID").eq("1"));
        //打印SQL,PreparedStatement SQL
         System.out.println(query.getSQL());
        //打印SQL
        System.out.println(query.getSQL(ParamType.INLINED));
    }


}

連接數據庫

import org.jooq.*;
import org.jooq.impl.DefaultDSLContext;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import static  com.*.jooqdemo.dao.Tables.*;

public class JOOQConnter {
    private static DSLContext create;
    private static Connection connection;
    static {
        //基於JDBC創建數據庫連接
        final String userName ="root";
        final String password ="*****";
        final String url ="jdbc:mysql://localhost:3306/jooq?serverTimezone=UTC";
        //Driver Conn

        try {
            connection =DriverManager.getConnection(url,userName,password);
            //需要注意,使用jdbc作爲JOOQ數據庫的連接方案時,連接的生命週期完全被交個用戶自己管理,JOOQ不會介入連接的提交或事務回滾和關閉。
            //在實際的ee項目應用中通常會使用datasource作爲數據庫連接方案,
            // 此時JOOQ自身提供了org.jooq.impl.DataSourceConnectionProvider作爲連接管理方案,此外也可以使用其他第三方管理工具
            create = new DefaultDSLContext(connection, SQLDialect.MYSQL);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    public static void main(String[] args) {
           if(create != null){
               SelectConditionStep query = create.select(AUTHOR.FIRST_NAME).from(AUTHOR).where(AUTHOR.ID.eq(1));
               System.out.println("執行腳本爲:"+query.getSQL());
               System.out.println(query.getBindValues());
               //查詢返回對象爲result
               Result result=query.fetch();
               System.out.println(String.format("返回結果爲:\n%s",result));
           }
        try {
            if (connection != null){
                connection.close();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

}

自定義JOOQ執行監聽器

其作用類似與mybtais攔截器

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.Duration;
import java.time.LocalDateTime;

import static com.*.jooqdemo.dao.Tables.AUTHOR;

public class JOOQExecuteListener extends DefaultExecuteListener {
    private static DSLContext create;
    private static Connection connection;
    static {
        //基於JDBC創建數據庫連接
        final String userName ="root";
        final String password ="*";
        final String url ="jdbc:mysql://localhost:3306/jooq?serverTimezone=UTC";
        //Driver Conn

        try {

            connection = DriverManager.getConnection(url,userName,password);

            Configuration configuration = new DefaultConfiguration().set(connection).set(SQLDialect.MYSQL);
            //註冊自定義執行監聽器
            //ExecuteListeners are a useful tool to...
            //
            //implement custom logging 自定義日誌
            //apply triggers written in Java  添加觸發器開關
            //collect query execution statistics 執行信息統計
            configuration.set(new DefaultExecuteListenerProvider(new JOOQExecuteListener()));
            create = new DefaultDSLContext(configuration);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }
    public static void main(String[] args) {
        if(create != null){
            SelectConditionStep query =          create.select(AUTHOR.FIRST_NAME).from(AUTHOR).where(AUTHOR.ID.eq(1));
            Result result=query.fetch();
            System.out.println(String.format("返回結果爲:\n%s",result));
        }
        try {
            if (connection != null){
                connection.close();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }
    private LocalDateTime beginDate;
    private String executeSql ;
    @Override
    //示例代碼用於統計SQL執行
    public void executeStart(ExecuteContext ctx) {
        System.out.println("++++開始執行++++++");
        beginDate = LocalDateTime.now();
        executeSql = ctx.query().getSQL();
        super.executeStart(ctx);
    }

    @Override
    public void executeEnd(ExecuteContext ctx) {
        super.executeEnd(ctx);
        Duration duration =  Duration.between(beginDate,LocalDateTime.now());
        System.out.println(String.format("%s執行時間爲%d    ms",executeSql,duration.toMillis()));
    }
}

jooq 事務

jooq本身提供了事務管理的功能,同時也支持事務託管給第三方如spring.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import static com.*.jooqdemo.dao.tables.Author.AUTHOR;

public class JOOQTransactionDemo {

    private DSLContext create;
    private Connection connection;

    private DSLContext initDSL() {
        //基於JDBC創建數據庫連接
        final String userName = "root";
        final String password = "*";
        final String url = "jdbc:mysql://localhost:3306/jooq?serverTimezone=UTC";
        //Driver Conn

        try {

            connection = DriverManager.getConnection(url, userName, password);

            Configuration configuration = new DefaultConfiguration().set(connection).set(SQLDialect.MYSQL);
            create = new DefaultDSLContext(configuration);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return create;
    }

    public void transaction() {
        create.transaction(configuration1 -> {
            DSL.using(configuration1)
                    .insertInto(AUTHOR, AUTHOR.ID,AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)
                    .values(6,"George", "Orwell")
                    .returning()
                    .fetchOne();
            //發生異常 事務回滾
            throw new RuntimeException("異常");


        });


    }

    public static void main(String[] args) {
        JOOQTransactionDemo jooqTransactionDemo = new JOOQTransactionDemo();
        jooqTransactionDemo.initDSL();
        jooqTransactionDemo.transaction();
    }
}

many to many

/**
 * 返回當前作者名下的書籍
 * author 和 book爲一對多關係
 * public class Author implements Serializable {
 *
 *     private static final long serialVersionUID = 223223344;
 *
 *     private Integer id;
 *     private String  firstName;
 *     private String  lastName;
 *     private List<Book> books;
 *     }
 * JOOQ本身並不沒有提供many to many 和one to many的支持,但通過擴展Mapper可以實現這樣的功能
 * https://www.petrikainulainen.net/programming/jooq/jooq-tips-implementing-a-read-only-   one-to-many-relationship/
 * @param id
 * @return
 */

public com.*.jooq.demo.dao.tables.pojos.Author getAuthorBooks(int id){
    
    Stream<com.*.jooq.demo.dao.tables.pojos.Author> stream = null;
    JdbcMapper<com.*.jooq.demo.dao.tables.pojos.Author> jdbcMapper = = JdbcMapperFactory.newInstance().addKeys("id","books").newMapper(com.*.jooq.demo.dao.tables.pojos.Author.class);
    try {
         Author a = Author.AUTHOR.as("a");
         Book b = Book.BOOK.as("b");
         ResultSet resultSet       =dslContext.select(a.ID.as("id"),a.FIRST_NAME.as("first_name"),
                 a.LAST_NAME.as("last_name"),b.ID.as("books_id"),b.BOOK_NAME.as("books_book_name"),b.PUBLISH_DATE.as("books_publish_date"))
                 .from(a).join(b).on(a.ID.eq(b.AUTHOR_ID)).where(a.ID.eq(id)).fetchResultSet();
         stream = jdbcMapper.stream(resultSet);
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    }
   return  stream.collect(Collectors.toList()).get(0);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章