如何使一个枚举映射到数据库表?

时间:2018-10-29 17:56:48

标签: java spring hibernate jpa

与此类似的问题: JPA Enum type as table in database

我有这样的枚举:

public enum OrderStatus {

    CREATED(0, true), 
    DRIVER_ASSIGNED(2, false), 
    ROUTE_ASSIGNED(4, false), 

    SUCCESSFULLY_FINISHED(20, true),

    CANCELLED(100, true);

    @Id
    final int id;
    final boolean visibleForClient;

    OrderStatus(int id, boolean visibleForClient) {
        this.id = id;
        this.visibleForClient = visibleForClient;
    }
}

,并希望将其显示为如下表格:


| ORDER STATUS         | ID | IS_VISIBLE_FOR_CLIENT |
|----------------------|----|-----------------------|
| CREATED              |  0 | TRUE                  |
| DRIVER_ASSIGNED      |  2 | FALSE                 |
| ROUTE_ASSIGNED       |  4 | FALSE                 |
| SUCCESSFULLY_FINISHED| 20 | TRUE                  |
| CANCELLED            |100 | TRUE                  |

1 个答案:

答案 0 :(得分:0)

看起来您正在寻找包含上述数据的表的初始数据输入。

  1. 您可以通过以下代码创建以上表格结构

    @Entity
    public class OrderTracker {
    
    @Id
    @Column(name = "ID")
    private int id;
    
    @Column(name = "IS_VISIBLE_FOR_CLIENT")
    private boolean visibleForClient;
    
    @Column(name = "ORDER_STATUS")
    @Enumerated(EnumType.STRING)
    private OrderStatus orderStatus;
    
    public OrderTracker(int id, boolean visibleForClient, OrderStatus orderStatus) {
        this.id = id;
        this.visibleForClient = visibleForClient;
        this.orderStatus = orderStatus;
    }
    
    
    //setter & getter 
    
    public enum OrderStatus {
    
        CREATED(0, true),
        DRIVER_ASSIGNED(2, false),
        ROUTE_ASSIGNED(4, false),
        SUCCESSFULLY_FINISHED(20, true),
        CANCELLED(100, true);
    
        final int id;
        final boolean visibleForClient;
        OrderStatus(int id, boolean visibleForClient) {
            this.id = id;
            this.visibleForClient = visibleForClient;
        }
    }
    

    }

  2. 要在表上创建初始数据,可以使用flyway或liquibase。