Rafael Teles
Rafael Teles

Reputation: 2748

Projection create new field

I have a class that represents a user date of birth in two separated fields

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

Is it possible to make a projection that exports the user age? I know we can concatenate fields using @Value.

Upvotes: 1

Views: 443

Answers (2)

Rafael Teles
Rafael Teles

Reputation: 2748

The easiest way to resolve the problem (if you can add code to the domain class) is to add a method in the user class like the one below:

@JsonIgnore
public int getAge() {
    return Period.between(
            LocalDate.of(dobYear, dobMonth, 1),
            LocalDate.now()
    ).getYears();
}

You can add the @JsonIgnore to block spring from exporting an "age" field when your entity is serialized. After adding that method you can create projection like the one below:

@Projection(name = "userAge ", types = {User.class})
public interface UserAge {

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

}

Upvotes: 1

Cepr0
Cepr0

Reputation: 30409

Something like this, for example:

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);
}

Some info

Upvotes: 0

Related Questions