2017-07-25 84 views
0

我有一个代表出生在两个分开的领域投影创建新的领域

用户日期
public class User { 
    private int yearOfBirth; 
    private int monthOfBirth; 
} 

是否有可能作出这样的出口用户年龄的投影类?我知道我们可以使用@Value连接字段。

回答

0

来解决问题(如果你可以到域类添加代码)最简单的方法是在用户添加一个方法类像下面这样:

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

您可以添加@JsonIgnore从当你的实体是序列化导出一个“年龄”字段阻挡春天。添加该方法后,您可以创建投影像下面这样:

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

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

} 
0

这样的事情,例如:

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

一些info

+0

谢谢@ Cepr0,但我一直在寻找一种方式与投影做到这一点 –

+0

可以使用UserAgeDto作为投影,如图所示码。 –

+0

@RafaelTeles您应该提供更多信息 - 您需要什么,显示您的实体/回购,您需要的结果模板... – Cepr0