[英]When I do saveAndFlush on an entity object, I see hibernate generates 2 update queries. Why is it and how to avoid it?
These are the steps I am doing - 1.Load the entity 2.update few fields on the entity.这些是我正在做的步骤 - 1.加载实体 2.更新实体上的几个字段。 3.saveAndFlush
3.saveAndFlush
I see one update query with all 3 fields updated in Step#2.我看到一个更新查询,在步骤#2 中更新了所有 3 个字段。 Other update query is updating one of the 3 fields but the value is from Step#1 and not Step#2.
其他更新查询正在更新 3 个字段之一,但该值来自 Step#1 而不是 Step#2。
Can someone please help me figure out how to avoid that?有人可以帮我弄清楚如何避免这种情况吗?
EDIT- Added my classes.编辑-添加了我的课程。
@Entity
@DynamicUpdate
public class Enrollment
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Embedded
private Section sectionInformation = new Section();
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.REFRESH})
@JoinColumn(name = "student_id")
private Student student;
@Enumerated(EnumType.STRING)
private TakingExam takingExam;
}
public ResponseEntity controllerMethod(){
Enrollment enrollment = service.getEnrollment(enrollmentId);
if (enrollment == null)
{
return new ResponseEntity<>(NOT_FOUND);
}
Enrollment otherEnrollment = null;
if (check some condition)
{
otherEnrollment =
service.getEnrollment(request.someValue());
validator.validateOtherEnrollment(enrollment,
otherEnrollment, request.someValue());
}
enrollment.takingExam(request.getTakingExam());
if (otherEnrollment != null)
{
service.swapEnrollments(enrollment, otherEnrollment);
}
}
private void swapEnrollments(Enrollment enrollment, String userName){
///lots of validations
enrollment.setUpdatedBy(userName);
fromEnrollment.setUpdatedDate(new
Timestamp(System.currentTimeMillis()));
enrollmentRepo.saveAndFlush(enrollment); ---- THIS IS WHERE I SEE 2 UPDATE QUERIES AS PUT BELOW
}
update
enrollment
set
taking_exam=?,
updated_by=?,
updated_date=?
where
id=?
update
enrollment
set
taking_exam=?
where
This is what is happening in my code -这就是我的代码中发生的事情 -
This is what helped avoid intermediate auto flush这有助于避免中间自动刷新
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.