krtkush
krtkush

Reputation: 1528

How to ignore certain column from being fetched when using findBy.. in JPA

I have a User entity which has all the user's data including the password hash. I also have an API getUserDetails which performs a simple userRepository.findById(id) to get all the user's data. However, in the process it also returns the password hash which I don't want to.

One way to remove the password hash is to remove it from the service layer after all the data has been fetched. Like this -

fun getUserDetails(id: Long): Optional<User> {
        val user: Optional<User> = userRepository.findById(id)
        user.get().password = ""
        return user
    }

The output will be like this -

{
  "id": 4,
  "roles": "ADMIN",
  "userName": "user3",
  "emailId": "[email protected]",
  "password": "",
  "phoneNumber": "1234",
  "organisationName": "test",
  "isActive": true
}

The password value has been removed but the key still exists. I would like to get rid of that too.

Is there any other way which is more baked into JPA which I can use to achieve the said result?

Upvotes: 0

Views: 790

Answers (2)

Eklavya
Eklavya

Reputation: 18430

Use @get:JsonIgnore on the field to skip serialization of that in response.

Obviously you don't need to send the password hash in the response. You need the password in service, it just ignored when giving serialize the response.

Upvotes: 1

A.khalifa
A.khalifa

Reputation: 2496

You can add new layer called DTO, and using famous library modelmapper

Add this in your pom.xml

<dependency>
    <groupId>org.modelmapper</groupId>
    <artifactId>modelmapper</artifactId>
    <version>2.3.5</version>
</dependency>

Create bean to use modelmapper in your application main for example

@Bean
public ModelMapper modelMapper() {
    return new ModelMapper();
}

And then create class UserDto example

public class UserDto { 
 private Long id;
    String username;
    // standard getters and setters

    private UserDto convertToDto(User user) {
        UserDto userDto = modelMapper.map(user, UserDto);
        return userDto;
    }

}

In your controller or service

return convertToDto(userRepository.findById(id)); // wil return userDto

Hope useful.

Upvotes: 1

Related Questions