如何将 jooq 结果映射到各自的实体

How to map jooq result to their respective entities

我有这个 SQL 查询:

select question.*, 
  question_option.id 
from question 
left join question_option on question_option.question_id = question.id;

如何将获得的结果映射到实体。这样预期的结果应该是 谁能给出获得上述结果的示例代码

{
"id": 2655,
"type": "MCQSingleCorrect",
"difficultyLevel": "Advanced",
"question": "Which country are you from?",
"answer": null,
"marks": 1.5,
"negativeMarks": 0.5,
"hint": null,
"explanation": null,
"booleanAnswer": null,
"passage": null,
"isPassageQuestion": null,
"audioFile": null,
"videoFile": null,
"questionFiles": [],
"tags": [],
"updatedAt": "2021-12-21T11:57:03.229136Z",
"createdAt": "2021-12-21T11:57:03.229098Z",
"questionOptions": [
    {
        "id": 2719,
        "option": "India",
        "index": 1,
        "correct": false,
        "blank": null
    },
    {
        "id": 2720,
        "option": "Newzealand",
        "index": 1,
        "correct": false,
        "blank": null
    },
    {
        "id": 2721,
        "option": "England",
        "index": 1,
        "correct": true,
        "blank": null
    },
    {
        "id": 2722,
        "option": "Australia",
        "index": 1,
        "correct": false,
        "blank": null
    }
]}

您可以使用 jOOQ 编写查询并执行此操作:

Query result = em.createNativeQuery(query.getSQL());
query.getResultList() // or query.getSingleResult() depending what you need.

在此处阅读更多内容: https://www.jooq.org/doc/3.15/manual/sql-execution/alternative-execution-models/using-jooq-with-jpa/using-jooq-with-jpa-native/

JSON 可以直接使用 SQL (以及 jOOQ)获取。这里有些例子: https://72.services/use-the-power-of-your-database-xml-and-json/

我是从我们评论讨论的角度来回答的,我建议你中间不需要 JPA,因为你可以直接用 jOOQ 做每一个映射/投影。在这种情况下,如果您的目标客户是 JSON,为什么不直接使用 SQL/JSON 呢?您不是加入,而是像这样嵌套 collection:

ctx.select(jsonObject(
      key("id", QUESTION.ID),
      key("type", QUESTION.TYPE),
      ..
      key("questionOptions", jsonArrayAgg(jsonObject(
        key("id", QUESTION_OPTION.ID),
        key("option", QUESTION_OPTION.OPTION),
        ..
      )))
    ))
   .from(QUESTION)
   .leftJoin(QUESTION_OPTION)
   .on(QUESTION_OPTION.QUESTION_ID.eq(QUESTION.ID))
   // Assuming you have a primary key here.
   // Otherwise, add also the other QUESTION columns to the GROUP BY clause
   .groupBy(QUESTION.ID)
   .fetch();

如果问题没有任何选项,这将生成一个 NULL JSON 数组。 You can coalesce() it to an empty array, if needed. There are other ways to achieve the same thing, you could also use MULTISET 如果您实际上不需要 JSON,而只是 Java object 的一些层次结构。

根据经验,当您使用 jOOQ 时,您的代码中几乎不需要 JPA,除非您真的依赖 JPA 的 object 图形持久化功能。