STACKJAVA

Code ví dụ jOOQ – Truy vấn dữ liệu (Select, Find)

Code ví dụ jOOQ – Truy vấn dữ liệu (Select, Find)

Trong ví dụ này mình sẽ thực hiện kết nối java tới MySQL sử dụng jOOQ để query dữ liệu

Tạo database

Đầu tiên mình tạo database library với table auto như sau:

CREATE 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`)
);

Khởi tạo dữ liệu:

INSERT INTO `library`.`author`(`id`, `first_name`, `last_name`) VALUES (1, 'Tolstoy', 'Lev Nikolayevich');
INSERT INTO `library`.`author`(`id`, `first_name`, `last_name`) VALUES (2, 'Shakespeare', 'William');
INSERT INTO `library`.`author`(`id`, `first_name`, `last_name`) VALUES (3, 'Conan Doyle', 'Arthur');
INSERT INTO `library`.`author`(`id`, `first_name`, `last_name`) VALUES (4, 'Hugo', 'Victor');
INSERT INTO `library`.`author`(`id`, `first_name`, `last_name`) VALUES (5, 'Rowling', 'J.K');

Tạo Maven Project

Thư viện sử dụng:

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>stackjava.com</groupId>
  <artifactId>jOOQDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
  </properties>

  <dependencies>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.16</version>
    </dependency>


    <dependency>
      <groupId>org.jooq</groupId>
      <artifactId>jooq</artifactId>
      <version>3.11.11</version>
    </dependency>
    <dependency>
      <groupId>org.jooq</groupId>
      <artifactId>jooq-meta</artifactId>
      <version>3.11.11</version>
    </dependency>
    <dependency>
      <groupId>org.jooq</groupId>
      <artifactId>jooq-codegen</artifactId>
      <version>3.11.11</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.jooq</groupId>
        <artifactId>jooq-codegen-maven</artifactId>
        <executions>
          <execution>
            <id>jooq</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>generate</goal>
            </goals>
            <configuration>
              <skip>${maven.generate-sources.skip}</skip>
            </configuration>
          </execution>
        </executions>
        <dependencies>
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
          </dependency>
        </dependencies>
        <configuration>
          <jdbc>
            <driver>com.mysql.cj.jdbc.Driver</driver>
            <url>jdbc:mysql://localhost:3306/library</url>
            <user>root</user>
            <password>admin1234</password>
          </jdbc>
          <generator>
            <name>org.jooq.codegen.JavaGenerator</name>
            <database>
              <name>org.jooq.meta.mysql.MySQLDatabase</name>
              <includes>.*</includes>
              <excludes />
              <inputSchema>library</inputSchema>
            </database>
            <target>
              <packageName>stackjava.com.jooq</packageName>
              <directory>src/main/java</directory>
            </target>
          </generator>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

Phần class entity mình sẽ thực hiện generate từ database

(Xem lại: Code ví dụ jOOQ, generate/tạo class từ table, database)

Thực hiện query dữ liệu:

package stackjava.com.jooq.test;

import java.sql.*;
import org.jooq.*;
import org.jooq.impl.DSL;
import stackjava.com.jooq.Tables;
import stackjava.com.jooq.tables.records.AuthorRecord;


public class DemoSelect {
    public static void main(String[] args) throws Exception {
          String user = "root";
          String password = "admin1234";
          String url = "jdbc:mysql://localhost:3306/library";
          try (Connection connection = DriverManager.getConnection(url, user, password)) {
              DSLContext dslContext = DSL.using(connection, SQLDialect.MYSQL);
              
              Result<AuthorRecord> result = dslContext.selectFrom(Tables.AUTHOR)
              		.where(Tables.AUTHOR.ID.greaterOrEqual(3)).fetch();
              for (AuthorRecord record : result) {
                  System.out.printf("id: %-5d first name: %-15s last name: %-10s", record.getId(), record.getFirstName(), record.getLastName());
                  System.out.println();
              }
              
//	            Result<Record2<Integer, String>> result = dslContext.select(Tables.AUTHOR.ID, Tables.AUTHOR.FIRST_NAME).from(Tables.AUTHOR).fetch();
//	            for (Record r : result) {
//	                Integer id = r.getValue(Tables.AUTHOR.ID);
//	                String firstName = r.getValue(Tables.AUTHOR.FIRST_NAME);
//	                System.out.printf("id: %-5d first name: %-10s", id, firstName);
//	                System.out.println();
//	            }
          }
          catch (Exception e) {
              e.printStackTrace();
          }
      }
}

Chạy file DemoSelect.java:

id: 3     first name: Conan Doyle     last name: Arthur    
id: 4     first name: Hugo            last name: Victor    
id: 5     first name: Rowling         last name: J.K

Thực hiện tìm kiếm dữ liệu, query like, query theo nhiều điều kiện

Ví dụ query các đối tượng có id lớn hơn 2 và firstName có chứa chữ ‘h’

package stackjava.com.jooq.test;

import java.sql.*;
import org.jooq.*;
import org.jooq.impl.DSL;

import stackjava.com.jooq.Tables;
import stackjava.com.jooq.tables.records.AuthorRecord;


public class DemoFind {
    public static void main(String[] args) throws Exception {
          String user = "root";
          String password = "admin1234";
          String url = "jdbc:mysql://localhost:3306/library";
          try (Connection connection = DriverManager.getConnection(url, user, password)) {
              DSLContext dslContext = DSL.using(connection, SQLDialect.MYSQL);
              Result<AuthorRecord> result = dslContext.selectFrom(Tables.AUTHOR)
              		.where(Tables.AUTHOR.ID.greaterThan(2)).and(Tables.AUTHOR.FIRST_NAME.like("%h%")).fetch();

              for (AuthorRecord record : result) {
              	System.out.printf("id: %-5d first name: %-15s last name: %-10s", record.getId(), record.getFirstName(), record.getLastName());
                  System.out.println();
              }
          }
          catch (Exception e) {
              e.printStackTrace();
          }
      }
}

Kết quả:

id: 4     first name: Hugo            last name: Victor

 

Okay, Done!

Download code ví dụ trên tại đây.

 

References:

https://www.jooq.org/doc/3.11/manual/sql-building/sql-statements/select-statement/