实体
@TableField ( fill = FieldFill . INSERT)
private String createByName;
@TableField ( fill = FieldFill . UPDATE)
private String updateBy;
填充类
package com. talents. application. config ;
import com. baomidou. mybatisplus. core. handlers. MetaObjectHandler ;
import com. talents. application. entity. dto. Account ;
import com. talents. application. service. AccountService ;
import com. talents. application. utils. SpringUtils ;
import org. apache. ibatis. reflection. MetaObject ;
import org. springframework. security. core. context. SecurityContextHolder ;
import org. springframework. security. core. userdetails. User ;
import org. springframework. stereotype. Component ;
import java. util. Date ;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill ( MetaObject metaObject)
{
String userId = "system" ;
String userName = "system" ;
User user = null ;
try
{
user = ( User ) SecurityContextHolder . getContext ( ) . getAuthentication ( ) . getPrincipal ( ) ;
} catch ( Exception e)
{
}
if ( user != null )
{
AccountService accountService = SpringUtils . getBean ( AccountService . class ) ;
Account account = accountService. findAccountByJobNumber ( user. getUsername ( ) ) ;
if ( account != null )
{
userId = account. getId ( ) ;
userName = account. getName ( ) ;
}
}
this . setFieldValByName ( "createTime" , new Date ( ) , metaObject) ;
this . setFieldValByName ( "createBy" , userId, metaObject) ;
this . setFieldValByName ( "createByName" , userName, metaObject) ;
}
@Override
public void updateFill ( MetaObject metaObject)
{
String userId = "system" ;
User user = ( User ) SecurityContextHolder . getContext ( ) . getAuthentication ( ) . getPrincipal ( ) ;
if ( user != null )
{
AccountService accountService = SpringUtils . getBean ( AccountService . class ) ;
Account account = accountService. findAccountByJobNumber ( user. getUsername ( ) ) ;
if ( account != null )
{
userId = account. getId ( ) ;
}
}
this . setFieldValByName ( "updateTime" , new Date ( ) , metaObject) ;
this . setFieldValByName ( "updateBy" , userId, metaObject) ;
}
}