如何将 @ManyToOne 关联映射到 SQL 查询的结果

use*_*031 4 java sql hibernate join many-to-one

我们正在开展一个迁移项目,我们正在从 HBM 文件迁移到注释。

当我尝试在属性上设置值时,我们面临重复的列映射问题,该属性基本上是同一类的实例。

public class Salary{

    // All the below are coming from lookup table like empLookUp, MonthLookup, 
    // YearLookup, CurrencyLookUp and they are joined using their primary key

    private int empId;
    private int month;
    private int year;
    private String currency;

    // Issue here: previousMonthSalary actually needs to be populated when the 
    // Salary is loaded, but for previous month. How do I achieve this.

    private Salary previousMonthSalary;

}
Run Code Online (Sandbox Code Playgroud)

如何绘制地图previousMonthSalary

Vla*_*cea 5

最有可能的是,您需要使用@JoinFormula注释:

@ManyToOne(fetch = FetchType.LAZY)
@JoinFormula("(" +
    "SELECT s.id " +
    "FROM salary s " +
    "WHERE s.empId = empId " +
    "AND CASE WHEN month = 1 THEN s.year + 1 = year AND s.month = 12 ELSE s.year = year AND s.month - 1 = month END "
")")
private Salary previousMonthSalary;
Run Code Online (Sandbox Code Playgroud)