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

时间:2017-11-20 19:32:07

标签: 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;

}

如何映射previousMonthSalary

2 个答案:

答案 0 :(得分:1)

正如我在this article中解释的那样,您很可能需要使用@JoinFormula annotation

@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;

答案 1 :(得分:0)

希望在previousMonthSalary变量中使用lazy fetch将解决您的问题。

@ManyToOne(fetch=fetchType.Lazy) 
private Salary previousMonthSalary;