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 *




Enter Captcha Here :