Search code examples
javaspringjava-8entityjooq

How to get an entity-related object correctly


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?


Solution

  • 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<?> result =
    ctx.select()
       .from(ARTICLE)
       .join(FILE).on(ARTICLE.FILE_ID.eq(FILE.ID))
       .fetch();