在我的服务类中,我尝试更新一个实体(及其许多子实体)并希望在同一事务中使用更新的记录。表中的数据正在更新,但即使调用
EntityManager's
lush()、clear() 或refresh() 后上下文也没有更新。
我在问题和答案实体之间有一对多的双向关系。
我有一个通用的实用程序类,应该提供基本的实用程序方法。这个想法是拥有将接口作为传递参数并执行一些通用逻辑的方法,以最大限度地减少几乎相似实体之间的重复。
Util方法包括:
@Transactional(value = TxType.REQUIRES_NEW)
public boolean updateAnswer(IQuestionEntity quesEntity, List<String> answerValues) {
// Does perform its logic, save,update,remove record
return true;
}
@Transactional(value = TxType.REQUIRES_NEW)
public void validateSurveyQuestion(IQuestionEntity iQuestionEntity) {
// update record
}
现在在下面的服务类中,我注释掉了 EntityManager 的调用,因为它们都没有反映数据库中已进行的更改,并且持久性上下文不会使用更新的结果进行更新。
假设问题是否有一个子答案并用另一条目更新。当以下方法返回时,答案表中的数据确实会更新。
Boolean ansUpdated = util.updateAnswer(headerSurveyQuestion, answerValues);
在调用第二个 util 方法之前,我想使用更新的记录。 I.E 有两个答案,但它仍然显示一个。不过,我可以确认数据已经持续存在。
服务方式:
public void updateAnswer(Long headerSurveyQuestionId, List<String> answerValues) {
HeaderSurveyQuestion headerSurveyQuestion = headerSruveyQuestionRepo.findById(headerSurveyQuestionId).get();
int size = headerSurveyQuestion.getAnswers().size();
Boolean ansUpdated = util.updateAnswer(headerSurveyQuestion, answerValues); // <---- Table does get updated when this call returns
String ansText = headerSurveyQuestion.getAnswers().get(0).getTextAnswer();
// headerSurveyQuestion = headerSruveyQuestionRepo.findById(headerSurveyQuestionId).get();
// entityManager.flush();
// entityManager.clear();
// headerSruveyQuestionRepo.f
// entityManager.refresh(headerSurveyQuestion);
// headerSurveyQuestion = headerSruveyQuestionRepo.findById(headerSurveyQuestionId).get();
headerSurveyQuestion.getAnswers().size();
size = headerSurveyQuestion.getAnswers().size();
util.validateSurveyQuestion(headerSurveyQuestion); // <---- Still points to old record (I want the updated records for parent and referenced child entities)
}
服务类也用
@Transactional
和两个 util 方法进行注释。
这是问题和答案实体之间的双向关系。
问题:(我尝试过 FetchType Lazy 和 Eager,还检查了 Cascade All,也删除了)
@OneToMany(mappedBy = "surveyQuestion", fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
private List<HeaderSurveyAnswer> answers;
答案:
@JsonIgnore
@ManyToOne
@JoinColumn(name = "header_survey_question_id")
private HeaderSurveyQuestion surveyQuestion;
您可以在从更新应答方法返回之前尝试拨打
headerSruveyQuestionRepo.saveAndFlush(headerSurveyQuestion)
吗?
与 save() 不同,saveAndFlush() 方法立即刷新数据库中的数据。当我们的业务逻辑需要在同一事务期间但在提交之前读取保存的更改时,我们需要使用此方法。