数据库字段名称为关键字,mybatisplus中的解决方法

最近在使用mybatisplus批量插入数据的时候,报了一个错误,代码提示语法错误:

### Error updating database.  Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'load,created_at,updated_at,data_source) VALUES   
('2023-06-01 13:00:00.0',5001,' at line 1

通过将sql拷贝到navicat中执行,发现是因为表字段 load 是系统关键字,作为关键字是可以通过波浪号注释的,如下:

INSERT INTO data_history_load_ele_data (`date`,`load`,created_at,updated_at,data_source) VALUES ('2023-06-01 11:00:00.0', 5000, '2023-06-01 11:00:00.0', '2023-06-01 11:00:00.0','上海');

但是因为是使用的mybatisplus 批量插入,没有使用xml,无法直接对sql进行编辑,一时之间没有想到更好的解决方法。

后面在检查对应的实体bean时,灵光一现,初始bean如下:

@Getter
@Setter
@TableName(value = "data_history_load_ele_data")
public class HistoryBaseData implements Serializable {
    
    

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private LocalDateTime date;

    private BigDecimal load;

    private LocalDateTime createdAt;

    private LocalDateTime updatedAt;

    private String dataSource;

}

既然mybatis plus可以指定表名,自然也应该支持指定字段名,在指定字段名的时候,就可以将字段名用波浪号注释起来。

@Getter
@Setter
@TableName(value = "data_history_load_ele_data")
public class HistoryBaseData implements Serializable {
    
    

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private LocalDateTime date;

    @TableField("`load`")
    private BigDecimal load;

    private LocalDateTime createdAt;

    private LocalDateTime updatedAt;

    private String dataSource;

}

在增加@TableField注解之后,重新启动服务,批量插入数据果然成功了。

猜你喜欢

转载自blog.csdn.net/qq_42740899/article/details/131326221