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

将 jOOQ 与 JPA 实体结合使用

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

这些章节的目标是描述如何在你有充分理由的情况下这样做。 但是,大多数情况下,最好直接使用 jOOQ 执行查询,尤其是在您想使用 jOOQ 的更高级功能时。 这篇博文说明了直接使用 jOOQ 执行查询的各种原因

通过原生查询 API 获取实体的最简单方法是将实体类传递给原生查询方法。 以下示例将 jOOQ 查询结果映射到 JPA 实体(来自上一节)。 只需添加以下实用程序方法

public static <E> List<E> nativeQuery(EntityManager em, org.jooq.Query query, Class<E> type) {

    // Extract the SQL statement from the jOOQ query:
    Query result = em.createNativeQuery(query.getSQL(), type);

    // Extract the bind values from the jOOQ query:
    List<Object> values = query.getBindValues();
    for (int i = 0; i < values.size(); i++) {
        result.setParameter(i + 1, values.get(i));
    }

    // There's an unsafe cast here, but we can be sure that we'll get the right type from JPA
    return result.getResultList();
}

请注意,如果您正在使用自定义数据类型绑定,请确保也考虑到这些。 例如,如下所示

static List<Object[]> nativeQuery(EntityManager em, org.jooq.Query query, Class<E> type) {

    // Extract the SQL statement from the jOOQ query:
    Query result = em.createNativeQuery(query.getSQL(), type);

    // Extract the bind values from the jOOQ query:
    int i = 1;
    for (Param<?> param : query.getParams().values())
        if (!param.isInline())
            result.setParameter(i++, convertToDatabaseType(param));

    return result.getResultList();
}

static <T> Object convertToDatabaseType(Param<T> param) {
    return param.getBinding().converter().to(param.getValue());
}

使用上面简单的 API,我们已经准备好编写复杂的 jOOQ 查询并将它们的结果映射到 JPA 实体

List<JPAAuthor> authors =
nativeQuery(em,
    DSL.using(configuration)
       .select()
       .from(AUTHOR)
       .orderBy(AUTHOR.ID)
, JPAAuthor.class);

authors.forEach(author -> {
    System.out.println(author.firstName + " " + author.lastName + " wrote");

    books.forEach(book -> {
        System.out.println("  " + book.title);
    });
});

反馈

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

The jOOQ Logo