[英]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.我有一个User
实体,其中包含所有用户数据,包括密码 hash。 I also have an API getUserDetails
which performs a simple userRepository.findById(id)
to get all the user's data.我还有一个 API getUserDetails
执行简单的userRepository.findById(id)
来获取所有用户的数据。 However, in the process it also returns the password hash which I don't want to.但是,在此过程中,它还会返回我不想返回的密码 hash。
One way to remove the password hash is to remove it from the service layer after all the data has been fetched.删除密码 hash 的一种方法是在获取所有数据后将其从服务层中删除。 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 - output 会是这样的——
{
"id": 4,
"roles": "ADMIN",
"userName": "user3",
"emailId": "hello@outlook.com",
"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?有没有其他更适合 JPA 的方法来实现上述结果?
You can add new layer called DTO, and using famous library modelmapper
您可以添加名为 DTO 的新层,并使用著名的库modelmapper
Add this in your pom.xml将此添加到您的 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 以在应用程序主中使用 modelmapper
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
And then create class UserDto example然后创建 class UserDto 示例
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在您的 controller 或服务中
return convertToDto(userRepository.findById(id)); // wil return userDto
Hope useful.希望有用。
Use @get:JsonIgnore
on the field to skip serialization of that in response.在字段上使用@get:JsonIgnore
以跳过序列化作为响应。
Obviously you don't need to send the password hash in the response.显然您不需要在响应中发送密码 hash。 You need the password in service, it just ignored when giving serialize the response.您需要服务中的密码,它只是在给出序列化响应时被忽略。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.