spring - Spring JPA 瞬态列表未初始化
问题描述
由于我想在 JavaFX 中的实体类中使用 ObservableLists,最初我遇到了 Hibernate 默认使用的专用 List 实现和反射注入的问题。因此我决定让我的 Entity 类用 注释@Access(AccessType.PROPERTY)
,因为我想强制 Hibernate 使用我的 getter 和 setter 方法而不是反射。
在一个特定的类中,我有许多 List 属性,例如protected List<CostEstimate> costEstimates;
. 对于这些列表中的每一个,我都有相应地注释的 getter 和 setter。到目前为止一切顺利,这似乎有效。问题在于,在我的 UI 中,我不想显示所有随时间创建的 costEstimates,而只显示最后一个。所以我创建了一个方法public CostEstimate getLastCostEstimate()
,它只返回列表中的最后一个元素。由于 MySQL 数据库中没有匹配的列,因此此方法使用 @Transient 注释,因为它仅返回相关列表中的最后一个元素。
我的控制器类将实体绑定getLastCostEstimate()
到相应的 UI 元素。
在我的实体类的默认构造函数中,costEstimates 列表使用初始默认估计值进行初始化,这样getLastCostEstimate()
应该始终返回有意义的 CostEstimate。在调试器中,我可以看到这个初始化被执行了。但是,在运行时,costEstimates 列表为空,我得到一个 IndexOutOfBoundsException。我认为这与@Transient 注释有关?!我想知道我是否有编码或设计问题?我想我的问题是:如何在 JPA 实体类中建模这个“只给我列表中的最后一个元素”(没有太多样板代码)?
谢谢您的帮助!
为了您的方便,请找到以下一些相关的代码片段:
@Entity
@Inheritance
@Access(AccessType.PROPERTY) // JPA reading and writing attributes through their accessor getter and setter methods
public abstract class UserRequirement extends Requirement implements Serializable {
..
protected List<CostEstimate> costEstimates; // Money needed
..
protected UserRequirement() {
..
costEstimates = FXCollections.observableArrayList();
setLastCostEstimate(new CostEstimate(0));
..
}
..
@OneToMany(mappedBy="parent", orphanRemoval = true, cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
public List<CostEstimate> getCostEstimates() {
return costEstimates;
}
@SuppressWarnings("unused") // Used by JPA
public void setCostEstimates(List<CostEstimate> newCostEstimates) {
if(newCostEstimates != null) {
((ObservableList<CostEstimate>)costEstimates).setAll(newCostEstimates);
} else {
costEstimates.clear();
}
}
@Transient
public CostEstimate getLastCostEstimate() {
return costEstimates.get(costEstimates.size()-1);
}
public void setLastCostEstimate(CostEstimate costEstimate) {
if(costEstimate = null) {
return;
}
costEstimates.add(costEstimate);
}
..
}
解决方案
推荐阅读
- javascript - 承诺中的承诺
- r - 使用断点包:“数据错误:仅数据帧”
- javascript - 函数在 Firefox 中的空格键上被调用两次
- google-apps-script - 如何在谷歌应用程序脚本中获取光标位置?
- python - Colaboratory 和 Selenium:错误消息“geckodriver”可执行文件需要在 PATH 中
- r - R中两个3D点之间的距离
- unit-testing - junit mockito 对控制器和服务方法使用相同的对象
- tensorflow - Google Cloud 上的 Item to Item 推荐引擎
- python - 列表中的Python转义字符导致问题
- node-red - 红色节点未正确显示表值?