Hibernate find multiple entities by id, Exception (preparedStatement can have at most 65535 parameters)

185 views Asked by At

lets say we have a posgresql table "post". with 3 attribues :

  • id

  • comments

  • tags

    Given a list of posts ids we want to find all the entities with these ids and fetch at the same time the comments and the tags (with one single request) and not n requests( with n the size of ids list).

    To avoid the "cannot fetch mutliple bags excpetion" i had to do two hql request one for each bag(comments and tags).

@Query(value = """
SELECt p 
FROM Post p
LEFT JOIN FETCH p.tags
""")
List<Post> findAllByIdWithTags(@Param('ids') List<Long> listId);


@Query(value = """
SELECt p 
FROM Post p
LEFT JOIN FETCH p.comments
WHERE p in :posts
""")
List<Post> findAllByPostsWithOptions(@Param('posts') List<Posts> posts);

Then, in my service I can call the two requests to have at the end entities whith both tags and comments.

List<Posts> posts = dao.findAllByIdWithTags(listIds)
posts = dao.findAllByPostsWithOptions(posts)

This works fine until i try to pass a large number of ids, if I try with 70k ids I get the exception "preparedStatement can have at most 65535 parameters"

how can i solve this ?

Hybernate 6

Postgresql 14

SpirngBoot 3

0

There are 0 answers