Java 和 MySQL 中枚举的数据截断(java.sql.SQLException:数据截断...)

Data truncation for enum in Java and MySQL (java.sql.SQLException: Data truncated for ...)

我有一个自定义的 class,代表一个 .csv 文件结构,稍后读入此 class 的数组列表。它有以下标签:

public class InputFile {

public enum Status {
    IN_STOCK,
    OUT_OF_STOCK
}

private int lineNumber;
private String sku;
private Status statusCode;
private Date orderDate;

public InputFile(int lineNumber, String sku, Status status, Date orderDate) {
    this.lineNumber = lineNumber;
    this.sku = sku;
    statusCode = status;
    setOrderDate(orderDate);
}

public Status getStatusCode() {
    return statusCode;
}

public void setStatusCode(Status input) {
    statusCode = input;
}

这是简化的 .csv 文件:

LineNumber;SKU;Status;OrderDate
1;553555254;IN_STOCK;2018-04-21
2;668470653;IN_STOCK;2018-05-08
3;899395925;OUT_OF_STOCK;2018-06-06

当我将这些读入 arrayList 并将各个状态放在 consolse 上进行检查时,它正确显示(IN_STOCK、OUT_OF_STOCK)。但是,当我尝试将其插入数据库时​​,它被截断了:

java.sql.SQLException: Data truncated for column 'Status' at row 1

这里是数据库上传的代码:

try {
     String orderItemQuery = "INSERT INTO `order_processing`.`order_item` (`OrderItemId`, `OrderId`, `SalePrice`, `ShippingPrice`, `Sku`, `Status`)" + "VALUES (?, ?, ?, ?, ?, ?)";

     PreparedStatement orderItemStmt = conn.prepareStatement(orderItemQuery);
     for (InputFile i : CSVManager.getList())
     {
         orderItemStmt.setInt (1, i.getOrderItemId());
         orderItemStmt.setInt(2,i.getOrderId());
         orderItemStmt.setDouble (3, i.getSalePrice());
         orderItemStmt.setDouble (4, i.getShippingPrice());
         orderItemStmt.setString (5, i.getSku());
         orderItemStmt.setObject(6, InputFile.Status.valueOf(i.getStatusCode().toString()));
         orderItemStmt.execute();
        }
    }
    catch (Exception e)
    {
        ...
    }

这里是数据库 table:

的 .sql
create table order_item
(
  OrderItemId    int         not null
    primary key,
  OrderId        int         not null,
  SalePrice      decimal     not null,
  ShippingPrice  decimal     not null,
  TotalItemPrice decimal AS (ShippingPrice + SalePrice) not null,
  SKU            varchar(25) not null,
  Status         enum ('OUT_OF_STOCK', 'IN_STOCK') not null,
  constraint order_item_order_OrderId_fk
    foreign key (OrderId) references `order` (OrderId)
);

少了什么?为什么枚举被截断?

EDIT: The problem was that Java enum types have a different ordinal numbers then MYSQL has. Java starts counting from 0 while MYSQL starts from 1. To solve the difference, a modification needed in the ordinal list in my enums:

    public enum Status {
    OUT_OF_STOCK (1),
    IN_STOCK (2);

    private int status;

    private Status (final int status) {
        this.status = status;
    }

    public int getStatus() {
        return status;
    }
}

然后向数据库中插入数据是示例:

orderItemStmt.setInt(6, i.getStatusCode().getStatus());

在将数据保存到数据库时使用 Status.valueOf("IN_STOCK") 和 IN_STOCK.name()。

我相信 SQL 上的枚举类型存储为数字。它的大小是 1 或 2 个字节。如果要存储状态字段的文本版本,请将该列声明为 varchar。或者你应该存储状态的序号。