jeudi 11 octobre 2018

transform ResultSet into generic class where the class constructor is defined via a factory

I have defined a method to parse the result of a MySQl select query into a generic class.

This method looks like this:

public <T> List<T> selectFromDb(Class<T> _class, String tableName,
                                     String searchKeyName, String searchKeyValue)
    throws SQLException, IllegalAccessException,
    InstantiationException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException {

    List<T> listDbData = new ArrayList<>();

    final String selectQuery = String.format("select * from %s.%s where %s = ?;",
        schemaName, tableName, searchKeyName);
    PreparedStatement selectStatement = connection.prepareStatement(selectQuery);

    try {
        selectStatement.setString(1, searchKeyValue);
        ResultSet result = selectStatement.executeQuery();
        while (result.next()) {

            T t = _class.getDeclaredConstructor(ResultSet.class).newInstance(result);

            listDbData.add(t);
        }

        selectStatement.close();
    }catch (SQLException e) {
        log.error("Query failed:" + selectQuery);
        throw e;
    } finally {
        selectStatement.close();
    }

    return listDbData;
}

I use it to perform select on two database tables for which I have defined the schema.

Previously I had defined a schema for which the above function worked. The class looked like this.

   @Getter //lombok
   @Setter
    public class C extends A {
        private String varA;
        private String varB;
        private String varC;


       public C(String s1, String s2) {
        ...
        ...
       }

       public C (ResultSet resultSet) {
       ....
       ...
       }

       //Other class methods

    }

Now I defined a factory in order to make the class immutable. I want to know how to modify the selectFromDb code to handle the modified class.

public class CFactory {

      public C from(String s1, String s2) {
        C c;
        ...
        ...

        return c;
       }

       public C from(ResultSet resultSet) {
         C c;
         ....
         ...
         return c; 
         } 
}
@Builder
@Getter //lombok
public class C extends A{

        private final String varA;
        private final String varB;
        private final String varC;

        ....
        ....

}

Thanks. Swagatika

Aucun commentaire:

Enregistrer un commentaire