Java: JPA get column and field names map

Task: Write methods to get column and field names map in the input Entity class

Implementation:

   public static Map<String, String> entityColumnsFieldNames(Class entityClass) {
       Map<String, String> result = new HashMap<>();
       Field[] fields = entityClass.getDeclaredFields();

       for (Field field : fields) {
           Column col = field.getAnnotation(Column.class);
           if (col != null) {
               result.put(col.name(), field.getName());
           }
       }
       return result;
   }

and

   public static Map<String, String> entityFieldsColumnNames(Class entityClass) {
       Map<String, String> result = new HashMap<>();
       Field[] fields = entityClass.getDeclaredFields();

       for (Field field : fields) {
           Column col = field.getAnnotation(Column.class);
           if (col != null) {
               result.put(field.getName(), col.name());
           }
       }
       return result;
   }

Done.

Leave a Reply

Your email address will not be published. Required fields are marked *

3  +  7  =  

Skynin cache:
Array ( [cache mode] => capture [requestKey] => 83980145fa66efad7bb9ac8f1e8abb1203.sc [skycache_disable_capture] => false )