个人博客网:wushaopei.com
一、 JOOQ是啥?
JOOQ 是基于Java访问关系型数据库的工具包,轻量,简单,并且足够灵活,可以轻松的使用Java面向对象语法来实现各种复杂的sql。对于写Java的码农来说ORMS再也熟悉不过了,不管是Hibernate或者Mybatis,都能简单的使用实体映射来访问数据库。
- 但有时候这些 ‘智能’的对象关系映射又显得笨拙,没有直接使用原生sql来的灵活和简单,而且对于一些如:joins,union, nested selects等复杂的操作支持的不友好。
- JOOQ 既吸取了传统ORM操作数据的简单性和安全性,又保留了原生sql的灵活性,它更像是介于 ORMS和JDBC的中间层。对于喜欢写sql的码农来说,JOOQ可以完全满足你控制欲,可以是用Java代码写出sql的感觉来。
- 就像官网说的那样 :
get back in control of your sql
JOOQ的优点
相对于Hibernate或者其他ORMS的,JOOQ的编程模式有很大不同,强大的Fluent API使用起来非常方便和流畅。现在我们的项目(MaxWon)使用JOOQ已经在生产环境运行了很长的一段时间,从来没花太多时间折腾在数据访问层上面。对于开发来说感受最深的就是这货真的很简单很灵活
- DSL(Domain Specific Language )风格,代码够简单和清晰。遇到不会写的sql可以充分利用IDEA代码提示功能轻松完成。
- 保留了传统ORM 的优点,简单操作性,安全性,类型安全等。不需要复杂的配置,并且可以利用Java 8 Stream API 做更加复杂的数据转换。
- 支持主流的RDMS和更多的特性,如self-joins,union,存储过程,复杂的子查询等等。
- 丰富的Fluent API和完善文档。
- runtime schema mapping 可以支持多个数据库schema访问。简单来说使用一个连接池可以访问N个DB schema,使用比较多的就是SaaS应用的多租户场景。
二、示例
SQL语句:
SELECT AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME, COUNT(*)
FROM AUTHOR
JOIN BOOK ON AUTHOR.ID = BOOK.AUTHOR_ID
WHERE BOOK.LANGUAGE = 'DE'
AND BOOK.PUBLISHED > DATE '2008-01-01'
GROUP BY AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME
HAVING COUNT(*) > 5
ORDER BY AUTHOR.LAST_NAME ASC NULLS FIRST
LIMIT 2
OFFSET 1
Java代码:
create.select(AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME, count())
.from(AUTHOR)
.join(BOOK).on(AUTHOR.ID.equal(BOOK.AUTHOR_ID))
.where(BOOK.LANGUAGE.eq("DE"))
.and(BOOK.PUBLISHED.gt(date("2008-01-01")))
.groupBy(AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)
.having(count().gt(5))
.orderBy(AUTHOR.LAST_NAME.asc().nullsFirst())
.limit(2)
.offset(1)
三、创建数据库
我们要创建一个名为library
的数据库,和一个author
表,在表中插入zhang3
,li4
数据。
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`)
);
INSERT INTO `author` (`id`, `first_name`, `last_name`) VALUES ('1', '3', 'zhang'), ('2', '4', 'li');
四、添加MAVEN依赖
① 添加 JOOQ 依赖
dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq</artifactId>
<version>3.9.5</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq-meta</artifactId>
<version>3.9.5</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen</artifactId>
<version>3.9.5</version>
</dependency>
②添加 mysql 数据库驱动依赖 (根据连接的数据库而定)
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
五 、映射生成 author类的java类
这里,要使用jOOQ的命令行工具生成映射到author
表的Java类。
代码生成的最简单的方法是将jOOQ的3个jar
文件和MySQL Connector jar
文件复制到一个临时目录(本示例中目录是test-generated
), 然后创建一个如下所示的library.xml
(名字随意修改):
目录结构:
library.xml配置文件内容:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-3.9.2.xsd">
<!-- Configure the database connection here -->
<jdbc>
<driver>com.mysql.jdbc.Driver</driver>
<!-- 数据库url -->
<url>jdbc:mysql://localhost:3306/library?useUnicode=true&characterEncoding=UTF-8</url>
<!-- 数据库账号 -->
<user>root</user>
<!-- 数据库账号密码 -->
<password>root</password>
</jdbc>
<generator>
<!-- The default code generator. You can override this one, to generate your own code style.
Supported generators:
- org.jooq.util.JavaGenerator
- org.jooq.util.ScalaGenerator
Defaults to org.jooq.util.JavaGenerator -->
<name>org.jooq.util.JavaGenerator</name>
<database>
<!-- The database type. The format here is:
org.util.[database].[database]Database -->
<name>org.jooq.util.mysql.MySQLDatabase</name>
<!-- The database schema (or in the absence of schema support, in your RDBMS this
can be the owner, user, database name) to be generated -->
<inputSchema>library</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>
<!-- All elements that are excluded from your schema
(A Java regular expression. Use the pipe to separate several expressions).
Excludes match before includes, i.e. excludes have a higher priority -->
<excludes></excludes>
</database>
<target>
<!-- The destination package of your generated classes (within the destination directory) -->
<!-- 生成的包名,生成的类在此包下 -->
<packageName>test.generated</packageName>
<!-- The destination directory of your generated classes. Using Maven directory layout here -->
<!-- 输出的目录 -->
<directory>J:\IDEA_Work_Space\maven_jooq_demo\src\main\java</directory>
</target>
</generator>
</configuration>
在Windows中,cd
到test-generated
目录,执行以下命令:
注意jar包的版本号与您本地对应上,在这个例子中,jOOQ使用3.9.5,MySQL使用5.1.41。
java -classpath jooq-3.9.5.jar;jooq-meta-3.9.5.jar;jooq-codegen-3.9.5.jar;mysql-connector-java-5.1.41.jar; org.jooq.util.GenerationTool library.xml
如果一切正常,您应该在控制台输出中看到这些信息:
并会生成如下java文件:
六、连接到你的数据库
在工程中编写一个测试类Main.java
:
package com.jooq.cn;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import java.sql.Connection;
import java.sql.DriverManager;
import static test.generated.tables.Author.AUTHOR;
public class Main {
public static void main(String[] args) {
//用户名
String userName = "root";
//密码
String password = "root";
//mysql链接url
String url = "jdbc:mysql://localhost:3306/library";
Connection conn;
try {
//这是JDBC Mysql连接
conn = DriverManager.getConnection(url, userName, password);
//基于JOOQ实现的简单查询
//传入Connection连接对象、数据方言得到一个DSLContext的实例,然后使用DSL对象查询得到一个Result对象。
DSLContext using = DSL.using(conn, SQLDialect.MYSQL);
Result<Record> fetch = using.select().from(AUTHOR).fetch();
//for循环输出结果
for (Record record : fetch) {
Integer id = record.getValue(AUTHOR.ID);
String firstName = record.getValue(AUTHOR.FIRST_NAME);
String lastName = record.getValue(AUTHOR.LAST_NAME);
/**
* 控制台输出
* ID: 1 first name: 3 last name: zhang
* ID: 2 first name: 4 last name: li
*/
System.out.println("ID:"+id + "firstName"+ firstName + "lastName: " + lastName);
}
//关闭连接
conn.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
注意:DSLContext不会主动关闭连接,需要我们手动关闭。
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ Thank you for using jOOQ 3.9.5
ID:1firstName3lastName: zhang
ID:2firstName4lastName: li
Process finished with exit code 0