Home > Enterprise >  How can I make a generic Spring Service to find entities and return only some fields
How can I make a generic Spring Service to find entities and return only some fields

Time:01-25

I have made a service that uses the entity manager to retrieve an entity given its name:

    public Object getEntity(long resourceId, String resource) throws EntityNotFoundException {
        try{
            Class<?> cls = Class.forName("com.example.package.models."   resource);
            Object resourceOpt = findById(cls, resourceId);


            if(resourceOpt == null){
                throw new EntityNotFoundException("Resource "   resource   " could not be found with id: "   resourceId);
            }

            return resourceOpt;
        }catch (ClassNotFoundException ex){
            throw new EntityNotFoundException("Resource "   resource   " could not be found with id: "   resourceId);
        }

    }

Where the "findById" does this:

public <T, ID> T findById(Class<T> type, ID id) {
        return entityManager.find(type, id);
    }

This works perfectly fine but I have a problem.

If I try to get the "User", the entity manager will return all the fields, including the password:

{
    "id": 1,
    "firstname": "name",
    "lastname": "surname",
    "email": "[email protected]",
    "password": "password",
    "role": "USER",
    "enabled": true,
    "username": "[email protected]",
    "authorities": [
        {
            "authority": "USER"
        }
    ],
    "accountNonLocked": true,
    "credentialsNonExpired": true,
    "accountNonExpired": true
}

How can I make it to retrieve only some fields? Should I use DTOs or JsonField annotations?

CodePudding user response:

If you application does not need to write users and never wants to expose the password then you can remove password from com.example.package.models.User.

Otherwise you need to use a DTO.

  • Related