在数据表里给字段设置了默认值为0,但是在插入的时候不生效,数据表设计如下

 

通过数据表生成的实体类

查看代码
@Data
@TableName(value = "user")
@NoArgsConstructor
@AllArgsConstructor
public class UserEntity{

    @TableId
    @ApiModelProperty("Id")
    private Integer id;

    @ApiModelProperty("用户名")
    private String username;

    @ApiModelProperty("密码")
    private String password;

    @ApiModelProperty("性别")
    private Integer gender;

    @ApiModelProperty("创建时间")
    private LocalDateTime createTime;

    private Integer deleted;
}

 

使用mybatis-plus将数据插入到数据库中

查看代码
UserEntity userEntity = new UserEntity();
        userEntity.setId(5);
        userEntity.setGender(0);
        userEntity.setUsername("username");
        userEntity.setPassword("123214");

        LocalDateTime dateTime = LocalDateTime.now();
        userEntity.setCreateTime(dateTime);

        userService.save(userEntity);

 

 使用mybatis-plus的方法进行插入后,发现deleted的值是NULL,而不是已经设置好的默认值0

 

 通过日志查看mybatis-plus的插入SQL语句,发现SQL语句会将deleted赋值为NULL,所以数据库的默认值就不生效了

 

查看了mybatis-plus的官方文档,发现是不小心改了配置文件,导致生成的SQL语句会将NULL值插入到数据库中

原因:mybatis-plus的插入策略写成了ignored,在生成SQL语句时,就不会判断插入数据库的值是否为NULL

解决:将这段配置删掉,按照mybatis-plus默认的配置,会进行判断是否为NULL,就可以屏蔽NULL值,不会插入到数据库,数据表设置的默认值就生效了