Spring 投影创建新字段

Spring 投影创建新字段,spring,spring-data,Spring,Spring Data,我有一个类,它在两个单独的字段中表示用户的出生日期 public class User { private int yearOfBirth; private int monthOfBirth; } 是否可以进行导出用户年龄的预测?我知道我们可以使用。类似这样的东西连接字段,例如: public class UserAgeDto { private int yearOfBirth; private int monthOfBirth; public Use

我有一个类,它在两个单独的字段中表示用户的出生日期

public class User {
    private int yearOfBirth;
    private int monthOfBirth;
}

是否可以进行导出用户年龄的预测?我知道我们可以使用。

类似这样的东西连接字段,例如:

public class UserAgeDto {
    private int yearOfBirth;
    private int monthOfBirth;

    public UserAgeDto(int yearOfBirth, int monthOfBirth) {
        // constructor implementation...
    }

    public int getAge() {
        // age calculation...
    }
}

public interface UserRepo extends JpaRepository<User, Long> {

    @Query("select new com.example.myapp.dto.UserAgeDto(u.yearOfBirth, u.monthOfBirth) from User u where u = ?")
    UserAgeDto getUserAgeDto(User user);
}
public类UserAgeDto{
私人出生年份;
蒙托夫出生私人酒店;
公共用户年龄到(出生年份,出生月份){
//构造函数实现。。。
}
公共整数getAge(){
//年龄计算。。。
}
}
公共接口UserRepo扩展了JpaRepository{
@查询(“从用户u中选择new com.example.myapp.dto.UserAgeDto(u.yearOfBirth,u.monthOfBirth),其中u=?”)
UserAgeDto getUserAgeDto(用户用户);
}

有些

解决此问题的最简单方法(如果可以向域类添加代码)是在用户类中添加一个方法,如下所示:

@JsonIgnore
public int getAge() {
    return Period.between(
            LocalDate.of(dobYear, dobMonth, 1),
            LocalDate.now()
    ).getYears();
}
@Projection(name = "userAge ", types = {User.class})
public interface UserAge {

    @Value("#{target.getAge()}")
    Integer getAge();

}
您可以添加
@JsonIgnore
来阻止spring在序列化实体时导出“age”字段。添加该方法后,可以创建如下所示的投影:

@JsonIgnore
public int getAge() {
    return Period.between(
            LocalDate.of(dobYear, dobMonth, 1),
            LocalDate.now()
    ).getYears();
}
@Projection(name = "userAge ", types = {User.class})
public interface UserAge {

    @Value("#{target.getAge()}")
    Integer getAge();

}

谢谢@Cepr0,但我一直在寻找一种方法来实现这一点。您可以使用UserAgeDto作为投影,如代码所示。@RafaelTeles您应该提供更多信息-您到底需要什么,显示您的实体/repo,一个您需要的结果模板。。。