简体   繁体   English

来自 Spring JPA 查询的自定义结果

[英]Custom Result from Spring JPA Query

I have a User class and I want to pull all the objects of that class from the database.我有一个用户 class 并且我想从数据库中提取该 class 的所有对象。 I am using Spring Data JPA and fetching data using @Query .我正在使用 Spring 数据 JPA 并使用@Query获取数据。 Is there a way I can hide partial digits of phone number of user.有没有办法可以隐藏用户电话号码的部分数字。 Something like converting 123-456-7890 to 123-XXX-XXXX.比如将 123-456-7890 转换为 123-XXX-XXXX。

 @Query(value = "SELECT u FROM User u ORDER BY u.name")
 List<User> getAllUsers();

I am using user object at multiple locationsin the code, so fetching and updating records everytime will be very time consuming and users will grow over the time so it will also affect the performance.我在代码中的多个位置使用用户 object,因此每次获取和更新记录将非常耗时,并且用户会随着时间的推移而增长,因此也会影响性能。

Is there any way(some post processors or anything) which can handle it while populating data into object after fething from database.有什么方法(一些后处理器或任何东西)可以处理它,同时在从数据库中获取数据后将数据填充到 object 中。

Any pointers will be very helpful.任何指针都会非常有帮助。

Thanks.谢谢。

You can convert your data when fetching using Attribute converter.您可以在使用属性转换器获取时转换您的数据。

public class PhoneNumberAttributeConverter implements AttributeConverter<String, String> {
    @Override
    public String convertToDatabaseColumn(String value) {
        return value;
    }
    @Override
    public String convertToEntityAttribute(String a) {
        String value = a.substring(0, 3) + s.substring(3).replaceAll("[0-9]", "X");
        return value;
    }
}

And use it on field并在现场使用

@Convert(converter = PhoneNumberAttributeConverter.class)
private String phoneNumber;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM