Introduction

Download and run jOOQ in 6 easy steps:

Preparation: Download jOOQ and your SQL driver

If you haven't already downloaded them, download jOOQ:
https://sourceforge.net/projects/jooq/files/Release/

Alternatively, you can create a Maven dependency:

<dependency>
  <groupId>org.jooq</groupId>
  <!-- artefacts are jooq, jooq-meta, jooq-codegen -->
  <artifactId>jooq</artifactId>
  <version>2.0.0</version>
</dependency>

For this example, we'll be using MySQL. If you haven't already downloaded MySQL Connector/J, download it here:
http://dev.mysql.com/downloads/connector/j/

Step 1: Create a SQL database and a table

We're going to create a database called "guestbook" and a corresponding "posts" table. Connect to MySQL via your command line client and type the following:

CREATE DATABASE guestbook;

CREATE TABLE `posts` (
  `id` bigint(20) NOT NULL,
  `body` varchar(255) DEFAULT NULL,
  `timestamp` datetime DEFAULT NULL,
  `title` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

Step 2: Generate classes

In this step, we're going to use jOOQ's command line tools to generate classes that map to the Posts table we just created. More detailed information about how to set up the jOOQ code generator can be found here:
http://www.jooq.org/manual/META/Configuration/

The easiest way to generate a schema is to copy the jOOQ jar files (there should be 3) and the MySQL Connector jar file to a temporary directory. Then, create a guestbook.xml that looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-2.0.4.xsd">
  <!-- Configure the database connection here -->
  <jdbc>
    <driver>com.mysql.jdbc.Driver</driver>
    <url>jdbc:mysql://localhost:3306/guestbook</url>
    <user>root</user>
    <password></password>
  </jdbc>

  <generator>
    <!-- The default code generator. You can override this one, to generate your own code style
         Defaults to org.jooq.util.DefaultGenerator -->
    <name>org.jooq.util.DefaultGenerator</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 owner, user, database name) to be generated -->
      <inputSchema>guestbook</inputSchema>

      <!-- All elements that are generated from your schema (several Java regular expressions, separated by comma)
           Watch out for case-sensitivity. Depending on your database, this might be important! -->
      <includes>.*</includes>

      <!-- All elements that are excluded from your schema (several Java regular expressions, separated by comma).
              Excludes match before includes -->
      <excludes></excludes>
    </database>

    <generate>
      <!-- Primary key / foreign key relations should be generated and used.
           This will be a prerequisite for various advanced features
           Defaults to false -->
      <relations>true</relations>
    </generate>

    <target>
      <!-- The destination package of your generated classes (within the destination directory) -->
      <packageName>test.generated</packageName>

      <!-- The destination directory of your generated classes -->
      <directory>C:/workspace/MySQLTest/src</directory>
    </target>
  </generator>
</configuration>

Replace the username with whatever user has the appropriate privileges. You'll want to look at the other values and replace as necessary. Here are the two interesting properties:

generator.target.package - set this to the parent package you want to create for the generated classes. The setting of test.generated will cause the test.generated.Posts and test.generated.PostsRecord to be created

generator.target.directory - the directory to output to.

Once you have the JAR files and guestbook.xml in your temp directory, type this (use colons instead of semi-colons on UNIX/Linux systems):

java -classpath jooq-2.0.0.jar;jooq-meta-2.0.0.jar;jooq-codegen-2.0.0.jar;mysql-connector-java-5.1.18-bin.jar;. org.jooq.util.GenerationTool /guestbook.xml

Note the prefix slash before guestbook.properies. Even though it's in our working directory, we need to prepend a slash, as it is loaded from the classpath. Replace the filenames with your filenames. In this example, jOOQ 2.0.0 is being used. If everything has worked, you should see this in your console output:

Nov 1, 2011 7:25:06 PM org.jooq.impl.JooqLogger info
INFO: Initialising properties  : /guestbook.xml
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Database parameters
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: ----------------------------------------------------------
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO:   dialect                : MYSQL
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO:   schema                 : guestbook
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO:   target dir             : /Users/jOOQ/Documents/workspace/MySQLTest/src
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO:   target package         : test.generated
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: ----------------------------------------------------------
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Emptying                 : /Users/jOOQ/workspace/MySQLTest/src/test/generated
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Generating classes in    : /Users/jOOQ/workspace/MySQLTest/src/test/generated
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Generating schema        : Guestbook.java
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Generating factory       : GuestbookFactory.java
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Schema generated         : Total: 122.18ms
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Sequences fetched        : 0 (0 included, 0 excluded)
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Masterdata tables fetched: 0 (0 included, 0 excluded)
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Tables fetched           : 5 (5 included, 0 excluded)
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Generating tables        : /Users/jOOQ/workspace/MySQLTest/src/test/generated/tables
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: ARRAYs fetched           : 0 (0 included, 0 excluded)
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Enums fetched            : 0 (0 included, 0 excluded)
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: UDTs fetched             : 0 (0 included, 0 excluded)
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Generating table         : Posts.java
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Tables generated         : Total: 680.464ms, +558.284ms
Nov 1, 2011 7:25:07 PM org.jooq.impl.JooqLogger info
INFO: Generating Keys          : /Users/jOOQ/workspace/MySQLTest/src/test/generated/tables
Nov 1, 2011 7:25:08 PM org.jooq.impl.JooqLogger info
INFO: Keys generated           : Total: 718.621ms, +38.157ms
Nov 1, 2011 7:25:08 PM org.jooq.impl.JooqLogger info
INFO: Generating records       : /Users/jOOQ/workspace/MySQLTest/src/test/generated/tables/records
Nov 1, 2011 7:25:08 PM org.jooq.impl.JooqLogger info
INFO: Generating record        : PostsRecord.java
Nov 1, 2011 7:25:08 PM org.jooq.impl.JooqLogger info
INFO: Table records generated  : Total: 782.545ms, +63.924ms
Nov 1, 2011 7:25:08 PM org.jooq.impl.JooqLogger info
INFO: Routines fetched         : 0 (0 included, 0 excluded)
Nov 1, 2011 7:25:08 PM org.jooq.impl.JooqLogger info
INFO: Packages fetched         : 0 (0 included, 0 excluded)
Nov 1, 2011 7:25:08 PM org.jooq.impl.JooqLogger info
INFO: GENERATION FINISHED!     : Total: 791.688ms, +9.143ms

Step 3: Write a main class and establish a MySQL connection

Let's just write a vanilla main class in the project containing the generated classes:

// For convenience, always static import your generated tables and
// jOOQ functions to decrease verbosity:
import static test.generated.Tables.*;
import static org.jooq.impl.Factory.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Connection conn = null;

        String userName = "root";
        String password = "";
        String url = "jdbc:mysql://localhost:3306/guestbook";

        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(url, userName, password);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }
}

This is pretty standard code for establishing a MySQL connection.

Step 4: Write a query using jOOQ's DSL

Let's add a simple query:

GuestbookFactory create = new GuestbookFactory(conn);
Result<?> result = create.select().from(POSTS).fetch();

First get an instance of GuestbookFactory so we can write a simple SELECT query. We pass an instance of the MySQL connection to GuestbookFactory. Note that the factory doesn't close the connection. We'll have to do that ourselves.

We then use jOOQ's DSL to return an instance of Result. We'll be using this result in the next step.

Step 5: Iterate over results

After the line where we retrieve the results, let's iterate over the results and print out the data:

for (Record r : result) {
    Long id = r.getValue(POSTS.ID);
    String title = r.getValue(POSTS.TITLE);
    String description = r.getValue(POSTS.BODY);

    System.out.println("ID: " + id + " title: " + title + " desciption: " + description);
}

The full program should now look like this:

package test;

// For convenience, always static import your generated tables and
// jOOQ functions to decrease verbosity:
import static test.generated.Tables.*;
import static org.jooq.impl.Factory.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.jooq.Record;
import org.jooq.Result;

import test.generated.GuestbookFactory;
import test.generated.tables.Posts;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Connection conn = null;

        String userName = "root";
        String password = "";
        String url = "jdbc:mysql://localhost:3306/guestbook";

        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(url, userName, password);

            GuestbookFactory create = new GuestbookFactory(conn);
            Result result = create.select().from(POSTS).fetch();

            for (Record r : result) {
                Long id = r.getValue(POSTS.ID);
                String title = r.getValue(POSTS.TITLE);
                String description = r.getValue(POSTS.BODY);

                System.out.println("ID: " + id + " title: " + title + " desciption: " + description);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }
}

Step 6: Explore!

jOOQ has grown to be a comprehensive SQL library. For more information, please consider the manual:
http://www.jooq.org/manual/

... explore the Javadoc:
http://www.jooq.org/javadoc/latest/

... or join the news group:
https://groups.google.com/forum/#!forum/jooq-user

This tutorial is the courtesy of Ikai Lan. See the original source here:
http://ikaisays.com/2011/11/01/getting-started-with-jooq-a-tutorial/

FAQ

Before you go on and read the whole manual, there are a couple of interesting questions that you might want to consider:

Q: When I generate source code from MySQL, can I also use it on another database?
A: Yes! The generated Java code will work for all supported databases, not only for the database driver that you used when you generated the code.

Q: When I generate source code from my developer database, can I also use it on production?
A: Yes! You can map your schema at code generation time or at run time. See the manual for details.

Q: Can I use jOOQ without code generation?
A: Yes! You can define tables, fields, conditions using Strings. See the manual for details.

Q: Can I use jOOQ as a query builder and execute queries with Spring?
A: Yes! This has been done by other users and will be documented soon. See this Stack Overflow question for details.