Spring Boot / Spring Data / Hibernate / JPA Dynamically generating select statement based on columns sent from frontend

Viewed 22

I'm currently facing a unique scenario that I have been unable to successfully find an answer to that doesn't involve creating a custom repository implementation.

Currently I have an entity that maps to a table and has around 20 fields. These fields are read from the entity and sent to the user who can then select them in a list and send it back to the server. This is where I encounter the problem. From what it seems there is no way to pass in parameters to the select statement of a Spring Data query. A solution could be to change it to a nativeQuery and then build my own select string. The problem with this solution is that by switching it to a native query I am going to lose out on paging and being able to apply a predicate that is built with QueryDSL for the where clause. I am unsure what the best way forward is

Example:

Foo with fields: A, B, C, D, E, F, G

A user request to only be given a result for fields A and E

@Query("SELECT :selectString FROM FOO foo")
Page<Foo> getFoo(Predicate predicate, Pageable page, Bar selectString)

This would be ideal, however hibernate doesn't allow passing a parameter into the select clause unless you are inserting.

So to try to avoid this I saw that QueryDSL allows passing in literals so I tried that route.

@Autowired
private EntityManager entityManager;

JPAQueryFactory factory = new JPAQueryFactory(entityManager);
QFoo foo = QFoo.foo;
FooPredicate predicate = new FooPredicate();
factory.select(Expressions.constant("A")).from(foo).where(predicate).fetch();

But it ran into the same problem of not allowing select parameters into the select clause.

0 Answers
Related