Suppose you want to use basic Java, without any strategic framework. If you can guarantee that the name of this field will be equal to the column in the database, you can use the Reflection API (otherwise, create an annotation and define the name of the mapping there)
By FieldName
List<Field> fields = Arrays.asList(clazz.getDeclaredFields()); for(Field field: fields) { field.setAccessible(true); } List<T> list = new ArrayList<>(); while(resultSet.next()) { T dto = clazz.getConstructor().newInstance(); for(Field field: fields) { String name = field.getName(); try{ String value = resultSet.getString(name); field.set(dto, field.getType().getConstructor(String.class).newInstance(value)); } catch (Exception e) { e.printStackTrace(); } } list.add(dto); }
By annotation
@Retention(RetentionPolicy.RUNTIME) public @interface Col { String name(); }
DTO:
class SomeClass { @Col(name = "column_in_db_name") private String columnInDbName; public SomeClass() {}
Same but
while(resultSet.next()) { T dto = clazz.getConstructor().newInstance(); for(Field field: fields) { Col col = field.getAnnotation(Col.class); if(col!=null) { String name = col.name(); try{ String value = resultSet.getString(name); field.set(dto, field.getType().getConstructor(String.class).newInstance(value)); } catch (Exception e) { e.printStackTrace(); } } } list.add(dto); }
Thoughts
In fact, iterating over all fields may seem inefficient, so I will keep the mapping somewhere, and not be repeated every time. However, if our T is a DTO for the purpose of data transfer and will not contain downloads of unnecessary fields, this is normal. In the end, it is much better than using standard methods.
Hope this helps someone.
TEH EMPRAH
source share