【笔记】JOOQ学习笔记

前言

jOOQ generates Java code from your database and lets you build type safe SQL queries through its fluent API.(官网

添加依赖

pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>

<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq</artifactId>
<version>3.19.26</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
</build>

创建连接对象

1
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/database", "root", "password");

创建上下文对象

1
DSLContext dslContext = DSL.using(connection, SQLDialect.MYSQL);

JOOQ实现增删改查

1
2
3
4
dslContext.insertInto(DSL.table("table_name"))
.columns(DSL.field("field_name_1"), DSL.field("field_name_2"))
.values("value_1", "value_2")
.execute();

1
2
3
dslContext.deleteFrom(DSL.table("table_name"))
.where(DSL.field("field_name_1").eq(1))
.execute();

1
2
3
4
pdate(DSL.table("table_name"))
.set(DSL.field("field_name_2"), "value")
.where(DSL.field("field_name_1").eq(1))
.execute();

1
2
3
4
5
6
7
8
9
Result<Record> result = dslContext.select()
.from(DSL.table("table_name"))
.where(DSL.field("field_name_1").eq(1))
.fetch();

for (Record record : result) {
System.out.println(record.getValue("field_name_1"));
System.out.println(record.getValue("field_name_2"));
}

完成

参考文献

哔哩哔哩——程序指南