Update-record — это плагин mybatis. В сочетании с spring AOP он записывает изменения указанной таблицы запросов/данных до и после модификации, а также записывает журнал изменений в базу данных.
<dependency>
<groupId>io.geekidea.spring.boot</groupId>
<artifactId>update-record-mybatis-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
@Configuration
public class UpdateRecordConfig {
@Bean
public UpdateRecordMybatisInterceptor updateRecordMybatisInterceptor(){
return new UpdateRecordMybatisInterceptor();
}
}
@Slf4j
@Aspect
@Component
public class UpdateRecordAop extends UpdateRecordAopSupport {
/**
* Точка
*/
private static final String POINTCUT = "@annotation(io.geekidea.updaterecord.annotation.UpdateRecord)";
/**
* Метод выполняется перед
*
* @param joinPoint
* @throws Throwable
*/
@Before(POINTCUT)
@Override
protected void doBefore(JoinPoint joinPoint) throws Throwable {
super.doBeforeHandle(joinPoint);
}
/**
* Метод нормально выполняется и успешно возвращается
*
* @param joinPoint
* @param result
* @throws Throwable
*/
@AfterReturning(value = POINTCUT, returning = RESULT)
@Override
protected void doAfterReturning(JoinPoint joinPoint, Object result) throws Throwable {
super.doAfterReturningHandle(joinPoint, result);
}
/**
* Обработка исключений
*
* @param exception
* @throws Throwable
*/
@AfterThrowing(value = POINTCUT, throwing = EXCEPTION)
@Override
protected void doAfterThrowing(Throwable exception) throws Throwable {
super.doAfterThrowingHandle(exception);
}
@Override
protected String getToken(HttpServletRequest request) {
return super.getToken(request);
}
@Override
protected void handleUpdateRecord(UpdateRecordLog updateRecordLog, List<UpdateRecordTableLog> updateRecordTableLogs, Set<UpdateRecordColumnLog> updateRecordColumnLogs) {
// Необходимо самостоятельно дополнить текущий идентификатор пользователя и имя пользователя, IP-адрес соответствующего региона, информацию о примечаниях и т. д.
updateRecordLog.setUserId("1");
updateRecordLog.setUserName("admin");
updateRecordLog.setArea("上海");
updateRecordLog.setRemark("update...");
}
@Async
@Override
protected void save(UpdateRecordLog updateRecordLog, List<UpdateRecordTableLog> updateRecordTableLogs, Set<UpdateRecordColumnLog> updateRecordColumnLogs) {
super.save(updateRecordLog, updateRecordTableLogs, updateRecordColumnLogs);
}
}
@UpdateRecord(module = "user")
public class AccountController {
@Autowired
private AccountService accountService;
@GetMapping("/pay")
@UpdateRecord("支付")
public String pay(@RequestParam Long userId, @RequestParam BigDecimal money) throws Exception{
accountService.pay(userId,money);
return "支付成功";
}
}
@Data
@Accessors(chain = true)
@UpdateRecordTable(name = "tb_account", value = "账户")
public class Account implements Serializable {
private static final long serialVersionUID = -2852768164693452983L;
@UpdateRecordId
private Long id;
/**
* Идентификатор пользователя
*/
@UpdateRecordColumn(name = "user_id",value = "用户ID")
private Long userId;
/**
* Остаток
*/
@UpdateRecordColumn("余额")
private BigDecimal balance;
/**
* Используется для записи версии
*/
@UpdateRecordVersion
private Integer version;
@UpdateRecordColumn
private Date createTime;
private Date
``` ### 7. Информация о записях в базе данных
- Записи об изменениях сохраняются в следующих трёх таблицах:
```text
+--------------------------------+
| update_record_column_log |
| update_record_log |
| update_record_table_log |
+--------------------------------+
mysql> select * from update_record_log;
+-------------------+----------------------------------+---------+-----------+--------+-----------+--------+-----------------------------------+--------------+----------------------------+-------------+---------------------------------------------+-------------------+-------------+----------------+-------+----------------------+-------------------------------------------------------------------------+------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------+-------------+--------------+-----------------+--------------------+--------------------+-----------+---------+---------------------+-------------+
| id | commit_id | user_id | user_name | name | ip | area | path | url | server_name | module_name | package_name | class_name | method_name | request_method | token | thread_name | before_all_value | after_all_value | diff_all_value | update_all_desc | table_total | column_total | add_model_total | update_model_total | delete_model_total | remark | version | create_time | update_time |
+-------------------+----------------------------------+---------+-----------+--------+-----------+--------+-----------------------------------+--------------+----------------------------+-------------+---------------------------------------------+-------------------+-------------+----------------+-------+----------------------+-------------------------------------------------------------------------+------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------+-------------+--------------+-----------------+--------------------+--------------------+-----------+---------+---------------------+-------------+
| 98486541914996748 | faff46eb3fc442f1bd4649b33cb01e54 | 1 | admin | 支付 | 127.0.0.1 | 上海 | http://localhost:9000/account/pay | /account/pay | spring-boot-mybatis-sample | user | io.geekidea.updaterecord.samples.controller | AccountController | pay | GET | NULL | http-nio-9000-exec-1 | [{"balance":"1000.00","update_time":"2019-12-02 20:49:05","version":1}] | [{"balance":"999.00","update_time":"2019-12-03 00:26:26","version":1}] | {"table-0-tb_account-id-1":[{"name":"balance","before":"1000.00","after":"999.00","mode":2},{"name":"update_time","before":"2019-12-02 20:49:05","after":"2019-12-03 00:26:26","mode":2}]} | 余额 由 1000.00 修改为 999.00 update_time 由 2019-12-02 20:49:05 修改为 2019-12-03 00:26:26 | 1 | 2 | 0 | 2 | 0 | update... | v1.0 | 2019-12-03 00:26:27 | NULL | ```
#### 2. update_record_table_log запрос, соответствующий таблице с записями об изменениях
```text
mysql> select * from update_record_table_log;
+-------------------+----------------------------------+----------------------------+-------------+------------------------------------------------------------------+------------+------------+-------------+----------------+------------------+----------+-----------------------------------------------------------------------+----------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+---------------+-------------------------------------------------------------------------------------------------------+-------+----------------+-------------------+-------------------+--------+---------+---------------------+-------------+
| id | commit_id | server_name | module_name | method_id | table_name | table_desc | entity_name | id_column_name | id_property_name | id_value | before_value | after_value | diff_value | before_version | after_version | update_desc | total | add_mode_count | update_mode_count | delete_mode_count | remark | version | create_time | update_time |
+-------------------+----------------------------------+----------------------------+-------------+------------------------------------------------------------------+------------+------------+-------------+----------------+------------------+----------+-----------------------------------------------------------------------+----------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------+---------------+-------------------------------------------------------------------------------------------------------+-------+----------------+-------------------+-------------------+--------+---------+---------------------+-------------+
| 98486541914996749 | faff46eb3fc442f1bd4649b33cb01e54 | spring-boot-mybatis-sample | user | io.geekidea.updaterecord.samples.mapper.AccountMapper.updateById | tb_account | 账户 | Account | id | id | 1 | {"balance":"1000.00","update_time":"2019-12-02 20:49:05","version":1} | {"balance":"999.00","update_time":"2019-12-03 00:26:26","version":1} | [{"name":"balance","before":"1000.00","after":"999.00","mode":2},{"name":"update_time","before":"2019-12-02 20:49:05","after":"2019-12-03 00:26:26","mode":2}] | 1 | 2 | остаток изменён с 1000,00 на
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Опубликовать ( 0 )