Search code examples
javaspringhibernateannotations

Java Annotation To Insert In Database


I have a database that stores data in the key-value format, for example:

|---------------------|------------------|
|      Key            |     Value        |
|---------------------|------------------|
|      KEY_FOR_NAME   |     Abhishek     |
|---------------------|------------------|

Currently, to store data in this table, for each key I do something like:

String additionalInfoValue = "Abhishek";
AdditionalInfo additionalInfo = new AdditionalInfo(); //entity object
additionalInfo.setKey("KEY_FOR_NAME");
additionalInfo.setSolutionValue(additionalInfoValue);

There are a lot of key-value pairs that go into that table, so it leads to a lot of code like the one mentioned above.

What I want to do is to make some annotation like:

@StoreInTable("KEY_FOR_NAME")
String additionalInfoValue = "Abhishek";

This will save my data in the table and will avoid unnecessary code like the one mentioned above.

I use Spring with Hibernate in my project to make all the entities and database queries (HQL).


Solution

  • Well just a simple Java reflection problem if I understand you correctly. Something like below:

    Define @StoreInTable:

    @Target(FIELD)
    @Retention(RUNTIME)
    public @interface StoreInTable {
        String value();
    }
    

    Write a function that pack @StoreInTable setting for any instance to a list of AdditionalInfo :

    public class FooUtil {
    
        public static List<AdditionalInfo> packAdditionalInfo(Object instance) throws Exception {
            List<AdditionalInfo> result = new ArrayList<>();
            for (Field field : instance.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                StoreInTable storeInTable = field.getAnnotation(StoreInTable.class);
                if (storeInTable != null) {
                    AdditionalInfo info = new AdditionalInfo();
                    info.setKey(storeInTable.value());
                    info.setValue(field.get(instance).toString());
                    result.add(info);
                }
            }
            return result;
        }
    }
    

    To use it , define any class representing key value pair which may be :

    public class KeyValue {
    
        @StoreInTable("KEY1")
        String additionalInfoValue1 = "Abhishek";
    
        @StoreInTable("KEY2")
        String additionalInfoValue2 = "Keshri";
    }
    

    Then :

    List<AdditionalInfo> infoList = FooUtil.packAdditionalInfo(new KeyValue());
    for(AdditionalInfo info : infoList){
        //save the info one by one , in this case it would save (key=KEY1, value=Abhishek) and (key=KEY2 , value=Keshri)
        entityManage.persist(info);
    }