0

question simillary to this one: JPA Enum type as table in database

I have enum like this:

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;
    }
}

and want to see it as a table like this:


| 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                  |
stakowerflol
  • 979
  • 1
  • 11
  • 20
  • I think the best approach is to use custom converter or UserType. – tsolakp Oct 29 '18 at 18:02
  • Your approach is strange. If I look at the database table, I see an entity with three field: `id`, `orderStatus`, `isVisibleForClient` but your `enum` does not reflect that: either the `id`, `visibleForClient` must not be here, either you are writing the entity class but then it must not be an enum. – Al-un Oct 29 '18 at 19:11
  • 3
    Why would you need a table if you have an enum already? It is better to have one or the other to store this information. – buræquete Oct 29 '18 at 20:01

1 Answers1

0

Looks like you are looking for initial data entry to your table with the above data.

  1. You could create above table structure by the following code

    @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. To create initial data on the table you could use flyway or liquibase.

maruf571
  • 1,836
  • 2
  • 21
  • 18