Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning subset/subschema using spring data JPA

I'm building a REST API using spring framework and a ran into a not-so-interesting case that i don't seem to find a solution for.

So let's say that we have table Table1 with columns Col1, Col2, and Col3 and we have users of access level 1,2 and 3

Users of access level 3 are the only ones allowed to access Col3 along with all other columns, the rest are allowed to access anything else.

Moreover, i want the API to be able to return a subset of the fields based on the call, I.E: if a call was made to URL /table/list?fl=col1 only the the value of Col1 will be returned.

What i need to is a way to return this particular subset of the data on the API level, apparently spring data JPA doesn't allow returning a dynamic subset of the table.

I was wondering what could be the cleanest way to do this without completely giving up JPA or having to rewrite all the functions in all the entities.

like image 986
amrnablus Avatar asked Feb 20 '26 12:02

amrnablus


1 Answers

Let me give you my thoughts.

What i need to is a way to return this particular subset of the data on the API level, apparently spring data JPA doesn't allow returning a dynamic subset of the table.

This is not correct, JPA allow to retrieve some part of the entity, is not required to return the complete entity when you select specific columns in the query of @Query method as you are using jpql or native query you should only return a part of the entity and spring data automatically will return List, read more here

Now to manage the access to the methods I suggest implement something with Spring Security, it allow to annotate some methods with @PreAuthorize

@PreAuthorize("hasRole('ROLE_USER')")
public void create(Contact contact);    

which means that access will only be allowed for users with the role "ROLE_USER".

So it will restrict the execution depending on the role, so my suggestion is restrict the access based in the role and have several spring jpa methods to retrieve only the subset of columns according to the role.

Another option is just create the dynamic jpql and executing directly in the entityManager, it will give you the possibility to map using @SqlResultMapping to obtain directly entities not a list of objects.

like image 73
Koitoer Avatar answered Feb 22 '26 01:02

Koitoer