jOOQ - DSLContext API
jOOQ 中的 DSLContext 是什麼?
DSLContext 是一個介面,可在執行查詢時配置 jOOQ 的行為。它的引用或物件管理與資料庫的實際互動。此上下文 DSL 是您的 jOOQ 程式碼訪問與查詢執行相關的類和功能的主要入口點。
DSL 用於建立 SQL 查詢,而 DSLContext 用於執行這些查詢並與資料庫互動。
如何建立一個 DSLContext 物件?
您可以藉助 DSL 類的組成部分 **using()** 方法建立 DSLContext 的物件或引用。在此方法中,您可以傳遞預先存在的配置或即席引數(如連線和方言)來建立 DSLContext 物件。
// Create it from a pre-existing configuration DSLContext create = DSL.using(configuration); // Create it from ad-hoc arguments DSLContext create = DSL.using(connection, dialect);
jOOQ DSLContext 示例
讓我們看看如何使用 DSLContext API 執行讀取表中值的查詢。假設表名為 **employee**,幷包含以下值 −
| ID | 姓名 | 職務 |
|---|---|---|
| 1 | 阿曼 | 技術編寫員 |
| 4 | 維維克 | 開發人員 |
要使用 jOOQ 獲取此記錄,請在**src -> main -> java -> com.example.demo** 內建立一個包。**com.example.demo** 資料夾的名稱取決於您的專案名稱。在此包內建立一個 Java 類。我們已將包命名為 **service**,將 Java 類命名為 **EmployeeService.java**。您可以根據自己的喜好指定任何名稱。
將以下程式碼段複製並貼上到 **EmployeeService.java** 檔案中。
package com.example.demo.service;
import org.jooq.*;
import org.jooq.Record;
import org.jooq.impl.DSL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
@Service
public class EmployeeService {
private final DataSource dataSource;
@Autowired
public EmployeeService(DataSource dataSource) {
this.dataSource = dataSource;
}
public void run() {
// Create a DSLContext using the DataSource
DSLContext create = DSL.using(dataSource, SQLDialect.MYSQL);
// Manually define the table and columns
Table<?> employee = DSL.table("employee");
Field<Integer> id = DSL.field("id", Integer.class);
Field<String> name = DSL.field("name", String.class);
Field<String> jobTitle = DSL.field("job_title", String.class);
// Fetch the values from the employee table
Result<Record3<Integer, String, String>> result = create.select(id, name, jobTitle)
.from(employee)
.fetch();
// Print the results
for (Record record : result) {
Integer employeeId = record.get(id);
String employeeName = record.get(name);
String employeeJobTitle = record.get(jobTitle);
System.out.println("ID: " + employeeId + ", Name: " + employeeName + ", Job Title: " + employeeJobTitle);
}
}
}
現在,導航到 **com.example.demo** 資料夾中的 **DemoApplication.java** 檔案。編寫如下給出的程式碼 −
package com.example.demo;
import com.example.demo.service.EmployeeService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
private final EmployeeService demoApplication;
public DemoApplication(EmployeeService demoApplication) {
this.demoApplication = demoApplication;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
demoApplication.run();
}
}
當您執行此程式碼時,它將呼叫 **EmployeeService.java** 檔案並列印以下結果 −
ID: 1, Name: Aman, Job Title: Technical Writer ID: 4, Name: Vivek, Job Title: Developer
廣告