0

I have some entities like this (a post with some tags associated with):

@Entity
public class Post {

  @GeneratedId
  public Long id;

  @ManyToMany(cascade=CascadeType.PERSIST, fetch = FetchType.LAZY)
  public Set<Tag> tags = new HashSet<Tag>();

  ...
}

@Entity
public class Tag {

  @GeneratedId
  public Long id;
  public String name;

}

I have to make some requests that returns hundreds of Posts with filtering on tags.

Up to now, I have used standard queries returning some Post entities, then accessing the myPost.tags to create my POJO.

This is really time consuming because each time I create a POJO, I call myPost.tags which makes a request to get them. I thought it was a good idea to use the select new feature like this:

select distinct new PostDTO(p.id, t) from Post p left outer join p.tags as t where ...

with

public class PostDTO {
   public PostDTO(Long id, Tag[] tags) {...}
}

Unfortunately, due to JPQL: Receiving a Collection in a Constructor Expression the tags could not be passed as an array.

So my question: how can I do? Do I have to change my schema? or JPA has a feature that I've missed?

dao hodac
  • 361
  • 2
  • 5
  • 14
  • As per `JPQL` query BNF, you cannot have a multi-valued field in the `SELECT` clause. You can do a query that returns Tag, and manually load them into your DTO; not exactly much effort needed for that –  Oct 11 '17 at 07:05
  • That's what's happenning behind the scene when I was using the `Post` entity getter on `tags`. unfortunately, it means 1 request for the `Post` and 1 request for the `tags`of the `Post`. For an array of 1000 posts, it means 1001 requests, that is too long to process – dao hodac Oct 11 '17 at 08:09
  • Is the only solution to change the model and add a field that is a String and cats the different tags? – dao hodac Oct 16 '17 at 12:42
  • I was also looking for something similar, and the closest thing I could find to what you're asking (w/o relying on an extra library) was the post titled [How to fetch a one-to-many DTO projection with JPA and Hibernate](https://vladmihalcea.com/one-to-many-dto-projection-hibernate/) by @VladMihalcea – OzgurH Aug 08 '21 at 23:26

0 Answers0