我正在开展一些个人项目,但我有一个关于 hibernate 的问题。
我有一个这样的类结构:
@Entity
public class User {
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "fkIdCompanyUser")
private Company company = new Company();
}
但在公司内部我还有另一个加入。
@Entity
public class Company {
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "fkIdCompanyEstimateOption")
private EstimateOptions estimateOptions = new EstimateOptions();
}
现在我进行查询来获取估计选项。 但如果我这样做,它会加载很多不必要的东西。
@RequestMapping(value = "/estimateoptions")
public EstimateOptions getCompanyEstimateOptions(@AuthenticationPrincipal Principal user) {
User getuser = userDao.findByEmail(user.getName());
EstimateOptions estimateOptions = getuser.getCompany().getEstimateOptions();
return estimateOptions;
}
有更好的方法吗?
最佳答案
有很多方法可以进行此类优化。最简单的一种是通过延迟加载向 Company
和 EstimateOptions
添加双向关联。
Company
的示例(我没有测试。这只是一个草图。)
@Entity
public class Company {
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "fkIdCompanyEstimateOption")
private EstimateOptions estimateOptions = new EstimateOptions();
@OneToOne(mappedBy="company", fetch = FetchType.LAZY)
private User user;
}
并执行类似的操作(这是 HQL,但您也可以使用条件 API)
from EstimateOptions options inner join options.company company inner join company.user user where user.name = :userName
您可以看到HQL joined query to eager fetch a large number of relationships以获得更多想法。
已更新
我不确定,但也许你可以做这样的事情(没有额外的关联)
select options from User user inner join user.company company inner join company.estimateOptions options where user.name = :userName
关于java - Hibernate 嵌套 JoinColumns 会导致从数据库中进行大量查询,并包含不必要的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34166510/