I am working in dynamically mapping the values from Result Set to POJO using Java reflection. It is working, but if the column name is different from the field in pojo it is not getting mapped.
For ex: if my column name is ORD_ID and in my pojo it is orderId, the ord_id is not getting mapped with order id. Here is the logic i'm using below.Kindly suggest a solution or an idea. Thanks in advance !
int colCount = resultSet.getMetaData().getColumnCount();
for (int i = 0; i < colCount; i++)
{
columnNames.put(resultSet.getMetaData().getColumnName(i + 1).toLowerCase(), i);
}
List<T> results = new ArrayList<>();
while(resultSet.next())
{
T newObj = clazz.newInstance();
for (Field field : clazz.getDeclaredFields())
{
String fieldName = field.getName().toLowerCase();
if (columnNames.containsKey(fieldName))
{
final int index = columnNames.get(fieldName);
field.setAccessible(true);
field.set(newObj, resultSet.getObject(index+1));
}
}
results.add(newObj);
}
but if the column name is different from the field in pojo it is not getting mapped
Obviously, that wouldn't work since your code is written for that very purpose when both names match so I don't understand the surprise element.
Only way out that I can think of is a secondary global map of field name to DB Column name and you refer to it once columnNames.containsKey(fieldName)
is false. That map is a manual work and that manual work will always be there since only you as a developer know that which column maps to which field in the POJO. That can't be automated if both are different & external mapping needs to be fed to Java progarm.
That mapping can be kept in an external property file.
There are APIs like apache-commons-dbutils but again manual mapping wouldn't go away as you will have to provide that in your custom - org.apache.commons.dbutils.BeanProcessor
Something else can be done the lines of JPA entity generation tools where we attach something like below to POJO fields -
@Column(name = "ADDRESS_IND")
private String addressInd;
but that is again a manual work as far as mapping specification is concerned. I think, you can retrieve annotation value and construct your mapping.
How to get annotation class name, attribute values using reflection