赞
踩
1.新建 MyMetaObjectHandler
- package com.ruoyi.framework.config;
-
- import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
- import com.ruoyi.common.bean.LocalUser;
- import com.ruoyi.coupon.domain.CouponUser;
- import org.apache.ibatis.reflection.MetaObject;
- import org.springframework.stereotype.Component;
-
- import java.util.Date;
-
- /**
- * 自动插入时间和操作人id
- */
- @Component
- public class MyMetaObjectHandler implements MetaObjectHandler {
- @Override
- public void insertFill(MetaObject metaObject) {
- this.setFieldValByName("createTime",new Date(),metaObject);
- CouponUser user = LocalUser.getUser();
- if(user != null){
- this.setFieldValByName("createBy",String.valueOf(user.getId()),metaObject);
- }
- }
-
- @Override
- public void updateFill(MetaObject metaObject) {
- this.setFieldValByName("updateTime",new Date(),metaObject);
- CouponUser user = LocalUser.getUser();
- if(user != null){
- this.setFieldValByName("updateBy",String.valueOf(user.getId()),metaObject);
- }
- }
- }
2.待自动设置字段加注解
- public class BaseEntity implements Serializable
- {
-
- /** 创建者 */
- @TableField(fill = FieldFill.INSERT)
- private String createBy;
-
- /** 创建时间 */
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
- @TableField(fill = FieldFill.INSERT)
- private Date createTime;
-
- /** 更新者 */
- @TableField(fill = FieldFill.INSERT_UPDATE)
- private String updateBy;
-
- /** 更新时间 */
- @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
- @TableField(fill = FieldFill.INSERT_UPDATE)
- private Date updateTime;
- }
2.如果无效,则需要加入一下配置
- @Bean
- public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception
- {
- String typeAliasesPackage = env.getProperty("mybatis-plus.typeAliasesPackage");
- String mapperLocations = env.getProperty("mybatis-plus.mapperLocations");
- String configLocation = env.getProperty("mybatis-plus.configLocation");
- typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage);
- VFS.addImplClass(SpringBootVFS.class);
-
- final MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean ();
- sessionFactory.setDataSource(dataSource);
- sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
- sessionFactory.setMapperLocations(resolveMapperLocations(StringUtils.split(mapperLocations, ",")));
- sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
-
- //获取mybatis-plus全局配置
- GlobalConfig globalConfig = GlobalConfigUtils.defaults();
- //mybatis-plus全局配置设置元数据对象处理器为自己实现的那个
- globalConfig.setMetaObjectHandler(new MyMetaObjectHandler());
- sessionFactory.setGlobalConfig(globalConfig);
-
- return sessionFactory.getObject();
- }
至此完成
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。