如何正确获取与实体相关的对象

huangapple go评论94阅读模式
英文:

How to get an entity-related object correctly

问题

我大致有以下实体:

public class Article {
    private String name;
    private Long fileId;
}

正如您所见,它有一个名为 fileId 的字段,其中包含相关文件的 id,该文件也是一个实体。然而,文件不知道任何关于 Article 的信息,所以连接它们的唯一方式是 Article 中的 fileId 字段。因此,它们必须显式地关联起来,以免丢失。现在,要获取关联的文件,我必须为每个 Article 进行单独的数据库查询。也就是说,如果我想获取 10 个 Article 的列表,我需要连续 10 次请求数据库,并根据其 id 获取文件。这看起来非常低效。有什么更好的方法可以做到这一点吗?我使用 jooq,因此无法使用 JPA,也无法用文件对象替换 fileId 字段。有什么想法吗?

英文:

I have approximately the following entity:

public class Article {
    private String name;
    private Long fileId;
}

As you can see, it has a field fileld that contains the id of the associated file, which is also an entity. However, the file does not know anything about the Article, so the only thing that connects them is the fileId field in the Article. Therefore, they must be explicitly linked so as not to get lost. Now to get a linked file, I have to make a separate query to the database for each Article. That is, if I want to get a list of 10 Articles, I need to make a request to the database 10 times and get the file by its id. This looks very inefficient. How can this be done better? I use jooq, so I can't use JPA, so I can't substitute a file object instead of the fileId field. Any ideas?

答案1

得分: 1

以下是翻译好的内容:

我假设您的基础表格类似于以下内容:

create table file (
  id      bigint primary key,
  content blob
);
create table article (
  name    text,
  file_id bigint references file
);

在这种情况下,您可以使用如下单个查询将所有10个文件一次性获取到内存中:

Result<?> result =
ctx.select()
   .from(ARTICLE)
   .join(FILE).on(ARTICLE.FILE_ID.eq(FILE.ID))
   .fetch();
英文:

I'm going to make an assumption that your underlying tables are something like this:

create table file (
  id      bigint primary key
  content blob
);
create table article (
  name    text,
  file_id bigint references file
);

In case of which you can fetch all 10 files into memory using a single query like this:

Result&lt;?&gt; result =
ctx.select()
   .from(ARTICLE)
   .join(FILE).on(ARTICLE.FILE_ID.eq(FILE.ID))
   .fetch();

huangapple
  • 本文由 发表于 2020年10月22日 11:53:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/64475070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定