Avoid updating on update fields with tkmapper
In daily development, our MySQL
database table will have mtime
a field to record the last update time of a certain record. It is generally set to, on update
that is, if there is any change in this record, mtime
the value of the field will be automatically updated.
Under normal circumstances, mtime
fields have no business meaning. But in a recent development, I encountered a special case that mtime
has business meaning, so I want to modify other fields of the table without modifying it. If you use SQL
a statement, it is very simple, the code is as follows:
UPDATE student
SET grade = 'A', mtime = mtime
WHERE name = 'Ryan';
You can update the field values of all name
the field values in the table to .Ryan
grade
A
But it is a little more complicated to use , because there may be many records with all field values tkmapper
in the table , and each record is different. We must first query all eligible records , and then update according to the primary key. code show as below:name
Ryan
mtime
mtime
Weekend<Student> weekend = Weekend.of(Student.class, true, true);
weekend.weekendCriteria().andEqualTo(Student::getName, "Ryan");
List<Student> studentList = studentMapper.selectByExample(weekend);
studentList.forEach(student -> {
student.setGrade("A");
student.setMtime(student.getMtime());
studentMapper.updateByPrimaryKeySelective(student);
});
In this way, we can mtime
modify the value of the field we want to update without changing it.