可用版本: Dev (3.21) | 最新 (3.20) | 3.19 | 3.18 | 3.17 | 3.16 | 3.15 | 3.14 | 3.13 | 3.12 | 3.11

将 jOOQ 与 Spring 的 JdbcTemplate 一起使用

适用于 ✅ 开源版   ✅ 专业版   ✅ 企业版

很多人都在他们的项目中使用 Spring 强大的 org.springframework.jdbc.core.JdbcTemplate 来简化常见的 JDBC 交互模式,例如

  • 变量绑定
  • 结果映射
  • 异常处理

当向广泛使用 JdbcTemplate 的项目中添加 jOOQ 时,务实的第一步是将 jOOQ 用作 SQL 构建器,并将查询字符串和绑定变量传递给 JdbcTemplate 以执行。 例如,您可能有以下类来存储作者及其在我们商店中的书籍数量

public class AuthorAndBooks {
    public final String firstName;
    public final String lastName;
    public final int books;

    public AuthorAndBooks(String firstName, String lastName, int books) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.books = books;
    }
}

然后你可以编写以下代码

// The jOOQ part stays the same as always:
Book b = BOOK.as("b");
Author a = AUTHOR.as("a");
BookStore s = BOOK_STORE.as("s");
BookToBookStore t = BOOK_TO_BOOK_STORE.as("t");

ResultQuery<Record3<String, String, Integer>> query =
create.select(a.FIRST_NAME, a.LAST_NAME, countDistinct(s.NAME))
      .from(a)
      .join(b).on(b.AUTHOR_ID.equal(a.ID))
      .join(t).on(t.BOOK_ID.equal(b.ID))
      .join(s).on(t.BOOK_STORE_NAME.equal(s.NAME))
      .groupBy(a.FIRST_NAME, a.LAST_NAME)
      .orderBy(countDistinct(s.NAME).desc());

// But instead of executing the above query, we'll send the SQL string and the bind values to JdbcTemplate:
JdbcTemplate template = new JdbcTemplate(dataSource);
List<AuthorAndBooks> result = template.query(
    query.getSQL(),
    (r, i) -> new AuthorAndBooks(
        r.getString(1),
        r.getString(2),
        r.getInt(3)
    ),
    query.getBindValues().toArray()
);

这种方法可以帮助您逐步从使用 JdbcTemplate 迁移到仅 jOOQ 的执行模型。

反馈

您对此页面有任何反馈吗? 我们很乐意听到您的反馈!

The jOOQ Logo