mybatis-plus插入修改配置默认值的实现方式是什么

发布时间:2022-07-07 14:05:01 作者:iii
来源:亿速云 阅读:677

mybatis-plus插入修改配置默认值的实现方式是什么

在使用MyBatis-Plus进行开发时,我们经常需要在插入或修改数据时设置一些默认值。这些默认值可能是数据库中的默认值,也可能是业务逻辑中的默认值。本文将介绍如何在MyBatis-Plus中实现插入和修改时配置默认值的几种方式。

1. 使用数据库默认值

1.1 数据库表设计

在数据库表设计时,可以为某些字段设置默认值。例如:

CREATE TABLE user (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

在这个例子中,created_atupdated_at字段分别设置了默认值。created_at字段在插入时会自动设置为当前时间,updated_at字段在插入和更新时都会自动设置为当前时间。

1.2 MyBatis-Plus实体类

在MyBatis-Plus中,实体类可以如下定义:

@Data
public class User {
    private Long id;
    private String username;
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;
}

1.3 插入和更新操作

在插入和更新操作时,MyBatis-Plus会自动使用数据库的默认值:

User user = new User();
user.setUsername("test");
userMapper.insert(user); // createdAt和updatedAt会自动设置为当前时间

user.setUsername("new_test");
userMapper.updateById(user); // updatedAt会自动更新为当前时间

2. 使用MyBatis-Plus的自动填充功能

2.1 实现MetaObjectHandler

MyBatis-Plus提供了MetaObjectHandler接口,可以在插入和更新时自动填充字段。我们可以通过实现这个接口来设置默认值。

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createdAt", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
    }
}

2.2 实体类注解

在实体类中,使用@TableField注解标记需要自动填充的字段:

@Data
public class User {
    private Long id;
    private String username;

    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createdAt;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updatedAt;
}

2.3 插入和更新操作

在插入和更新操作时,MyBatis-Plus会自动调用MetaObjectHandler的实现类来填充字段:

User user = new User();
user.setUsername("test");
userMapper.insert(user); // createdAt和updatedAt会自动填充

user.setUsername("new_test");
userMapper.updateById(user); // updatedAt会自动更新

3. 使用MyBatis-Plus的全局配置

3.1 配置全局默认值

MyBatis-Plus允许在全局配置中设置默认值。可以通过MybatisPlusProperties来配置全局默认值。

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: deleted  # 逻辑删除字段
      logic-delete-value: 1        # 逻辑删除值
      logic-not-delete-value: 0    # 逻辑未删除值
      insert-strategy: not_null    # 插入策略
      update-strategy: not_null     # 更新策略

3.2 实体类注解

在实体类中,使用@TableField注解标记需要全局配置的字段:

@Data
public class User {
    private Long id;
    private String username;

    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createdAt;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updatedAt;

    @TableField(fill = FieldFill.INSERT)
    private Integer status = 1; // 默认值为1
}

3.3 插入和更新操作

在插入和更新操作时,MyBatis-Plus会根据全局配置自动填充字段:

User user = new User();
user.setUsername("test");
userMapper.insert(user); // createdAt、updatedAt和status会自动填充

user.setUsername("new_test");
userMapper.updateById(user); // updatedAt会自动更新

4. 使用MyBatis-Plus的SQL注入器

4.1 自定义SQL注入器

MyBatis-Plus允许通过自定义SQL注入器来实现默认值的插入和更新。可以通过继承AbstractSqlInjector来实现自定义SQL注入器。

public class MySqlInjector extends AbstractSqlInjector {

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
        List<AbstractMethod> methodList = new ArrayList<>();
        methodList.add(new InsertDefaultValue());
        methodList.add(new UpdateDefaultValue());
        return methodList;
    }
}

4.2 自定义插入和更新方法

在自定义的插入和更新方法中,可以设置默认值:

public class InsertDefaultValue extends AbstractMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = "INSERT INTO " + tableInfo.getTableName() + " (username, created_at, updated_at) VALUES (#{username}, NOW(), NOW())";
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addInsertMappedStatement(mapperClass, modelClass, "insertDefaultValue", sqlSource, new NoKeyGenerator(), null, null);
    }
}

public class UpdateDefaultValue extends AbstractMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = "UPDATE " + tableInfo.getTableName() + " SET username = #{username}, updated_at = NOW() WHERE id = #{id}";
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addUpdateMappedStatement(mapperClass, modelClass, "updateDefaultValue", sqlSource);
    }
}

4.3 注册SQL注入器

在Spring Boot中,可以通过配置类注册自定义的SQL注入器:

@Configuration
public class MyBatisPlusConfig {

    @Bean
    public MySqlInjector mySqlInjector() {
        return new MySqlInjector();
    }
}

4.4 插入和更新操作

在插入和更新操作时,可以调用自定义的插入和更新方法:

User user = new User();
user.setUsername("test");
userMapper.insertDefaultValue(user); // createdAt和updatedAt会自动填充

user.setUsername("new_test");
userMapper.updateDefaultValue(user); // updatedAt会自动更新

5. 总结

在MyBatis-Plus中,可以通过多种方式实现插入和修改时配置默认值。具体选择哪种方式,取决于业务需求和开发习惯。数据库默认值适用于简单的场景,自动填充功能适用于复杂的业务逻辑,全局配置适用于统一的默认值设置,而自定义SQL注入器则适用于高度定制化的需求。

通过合理使用这些方法,可以大大简化代码,提高开发效率。

推荐阅读:
  1. 如何解决mysql timestamp无法插入带默认值
  2. Java动态修改配置即时生效的方式WatchService

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mybatisplus

上一篇:微信小程序swiper轮播图组件如何使用

下一篇:Spring容器初始化register与refresh方法是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》