Avoid updating on update fields with tkmapper

Avoid updating on update fields with tkmapper

In daily development, our MySQLdatabase table will have mtimea field to record the last update time of a certain record. It is generally set to, on updatethat is, if there is any change in this record, mtimethe value of the field will be automatically updated.

Under normal circumstances, mtimefields have no business meaning. But in a recent development, I encountered a special case that mtimehas business meaning, so I want to modify other fields of the table without modifying it. If you use SQLa 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 namethe field values ​​​​in the table to .RyangradeA

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:nameRyanmtimemtime

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 mtimemodify the value of the field we want to update without changing it.

Guess you like

Origin blog.csdn.net/itigoitie/article/details/127364944