SoFunction
Updated on 2025-03-01

The solution to the Mybatis-Plus update time field not taking effect

background

Mybatis-Plus only enhances and does not change based on Mybatis, mainly to simplify development. The background of the project is Mybatis-Plus, but a problem was found during the running project. When using Mybatis-Plus to update data, the update field did not update the corresponding time as we expected.

The statement that creates this field is as follows:

 `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update time'

Cause analysis

Use Mybatis-Plus update method to update the corresponding data entity, for example:

()
// ....... Wait for the method

After these methods are used, it is found that no updateTime field data is updated.

Cause analysis:

When selectByld takes out old data from the database, then modify the field you want to modify, and then calls updateById, you will find that the updateTime field will not be updated. This is because selectByld can take out the old value of updateTime. When filling the policy path, it will determine that the attribute already has a value and will not be automatically filled, so updateTime will not be automatically updated. Moreover, the official does not directly provide a method of forced updates.

Check the fillStrategy method source code, we can also see that only if the attribute is not filled with values, the set method will be executed.

Solution

Solution 1

Set update time when updating

	TDZopenOrder openOrder = (orderId);
	(washOrderId);
	(());
	()

Solution 2

Set update time on entity

	public class TDZopenOrder {
	    @ApiModelProperty("Update time")
	    @TableField(update = "now()")
	    private LocalDateTime updateTime;
	}

Recommended method 2, so that you don’t need to set the update time every time, simplifying the code! ! !

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.