Book Image

jOOQ Masterclass

By : Anghel Leonard
Book Image

jOOQ Masterclass

By: Anghel Leonard

Overview of this book

jOOQ is an excellent query builder framework that allows you to emulate database-specific SQL statements using a fluent, intuitive, and flexible DSL API. jOOQ is fully capable of handling the most complex SQL in more than 30 different database dialects. jOOQ Masterclass covers jOOQ from beginner to expert level using examples (for MySQL, PostgreSQL, SQL Server, and Oracle) that show you how jOOQ is a mature and complete solution for implementing the persistence layer. You’ll learn how to use jOOQ in Spring Boot apps as a replacement for SpringTemplate and Spring Data JPA. Next, you’ll unleash jOOQ type-safe queries and CRUD operations via jOOQ’s records, converters, bindings, types, mappers, multi-tenancy, logging, and testing. Later, the book shows you how to use jOOQ to exploit powerful SQL features such as UDTs, embeddable types, embedded keys, and more. As you progress, you’ll cover trending topics such as identifiers, batching, lazy loading, pagination, and HTTP long conversations. For implementation purposes, the jOOQ examples explained in this book are written in the Spring Boot context for Maven/Gradle against MySQL, Postgres, SQL Server, and Oracle. By the end of this book, you’ll be a jOOQ power user capable of integrating jOOQ in the most modern and sophisticated apps including enterprise apps, microservices, and so on.
Table of Contents (26 chapters)
1
Part 1: jOOQ as a Query Builder, SQL Executor, and Code Generator
4
Part 2: jOOQ and Queries
11
Part 3: jOOQ and More Queries
16
Part 4: jOOQ and Advanced SQL
22
Part 5: Fine-tuning jOOQ, Logging, and Testing

Updating a primary key of an updatable record

As a good practice, a primary key should never be updated anyway. But, who am I to judge?!

By default, calling the store() method after changing (to a non-null value) the primary key of an updatable record previously loaded via jOOQ causes an INSERT statement to be executed. However, we can force jOOQ to generate and execute an UPDATE of the primary key via the withUpdatablePrimaryKeys() flag setting:

DSLContext derivedCtx = ctx.configuration().derive(
  new Settings().withUpdatablePrimaryKeys(true)).dsl();
 SaleRecord sr = derivedCtx.selectFrom(SALE)
    .where(SALE.SALE_ID.eq(2L))
    .fetchSingle();
 sr.setSaleId(new_primary_key);
 sr.store(); // UPDATE primary key

Of course, we can also update the primary key via an explicit UPDATE, and if you really have to do it, then go for this instead of a jOOQ flag:

ctx.update(SALE)
   .set(SALE.SALE_ID, sr.getSaleId...