Skip to content
Advertisement

How to insert all enums into database?

We have a list of ENUMS for different purposes.

Sample Enum:

public enum EJobTrackingType implements Lookup<EJobTrackingType> {

 //I want to save all these enums into database

  NOTIFY_SERVICE(230000001, 1,"Notify service",  "desc"),
  COMPLETED_SERVICE(230000002, 2,"Completed service",  "desc"),
  ..... //more than 100 enums like this
}

we use .sql file to save this enums,

 INSERT INTO FTTHAPP.TBL_LOOKUP (id, parent_lookup_id, group_id, group_name, code, name, desc) values (230000001, NULL, 23, 'JOB_TRACKING_TYPE',   1, 'NOTIFY_SERVICE', "desc")

Problem:

We need to write values two times (One in enum and another one .sql statement)

It seems not efficient way, Is any other way to save ENUMS to avoid this repetition?

Advertisement

Answer

From the above mentioned details what I understood is that we have to insert all the enums present in the java file to database.

The possible answer I think would be to iterate over all the enums and insert each of them to database.

EnumSet.allOf(EJobTrackingType.class)
            .forEach(eJob -> ejobRepository.saveAnFlush(eJob));

This is not the actual implementation though but it gives idea how we can proceed.

We can have a class mapping to the values that has to be stored marked as @Entity. Populate that class with values in Enums with the help of some adapter. And the entity class can be saved to database.

We can have some attribute to specify an insert or update has to be made. So that we can have some filter during the forEach of Enums.

This job can be ran on the start up of application where a new class which will handle this job can be annotated with @Configuration. If there are too many rows to be updated/inserted there might be a possibility of running this job in a separate thread.

I think this helps.. These are few things I thought of..

Advertisement