【发布时间】:2020-01-08 21:52:37
【问题描述】:
我有一个实体,例如 Employee,它包含一个 @Transient 对象薪水,它将从相关表/实体 DailyTimeRecord (DTR) 派生。 DTR 对象数据检索使用联接,并且它也在 Employee 对象中自动装配。 DTR 对象列表将作为计算 Salary 对象值的基础。
我在这里发现[1]:Why is my Spring @Autowired field null? 应该避免使用new 关键字,让IoC Container 创建对象。另外,我想避免使用new关键字,以尽量减少我的代码耦合,并尽可能保证未来的兼容性和支持可扩展性。因此,我有接口 Salary 并由 SalaryImpl 类实现。
但每次我尝试运行在瞬态属性 Salary 上自动装配的代码时,它始终为空。我在这里找到了根本原因 [2]:How to populate @Transient field in JPA? 在 JPA 中 Transient 将始终为空。
我将如何创建一个避免使用 new 关键字的对象,而它是一个瞬态属性?
实体类
@Entity
Class Employee implements Serializable {
//Attributes from DB here
@OneToMany
@JoinColumn(name="empNumber", referencedColumnName = "empNumber")
private List<DTR> dtr;
@Autowired
@Transient
private Salary salary;
//getters ang setters here
public double computeSalary(){
}
}
薪资界面
public interface Salary {
public double computeSalary(List<Benefit> benefits, List<Deduction> deductions);
}
接口工资的基类/实现类
@Service
public class SalaryImpl implements Salary, Serializable {
//other attributes here
//getter and setters
//other methods
@Override
public double computeSalary(List<Benefit> benefits, List<Deduction> deductions){
return 0;
}
}
【问题讨论】:
标签: java spring-boot autowired transient