samedi 20 janvier 2018

Java generics and reflection to create and set model for SimpleJdbcCall in Spring

I am trying to use reflection and generics to create models using SimpleJdbcCall, so that I won't have to create a distinct mapper per model.

Here is my implementation so far:

public abstract class DAO<T extends ModelBase> {

    private final DataSource dataSource;

    DAO(final DataSource dataSource) {
        this.dataSource = dataSource;
    }

    protected List<T> buildModels(SqlParameterSource sqlSource, Class modelBase) {
        final String RESULT_SET = "RESULT_SET";
        return (List<T>)new SimpleJdbcCall(dataSource)
            .withCatalogName("someCatalog")
            .withSchemaName("someSchema")
            .withProcedureName(getProcForModel(modelBase))
            .returningResultSet(RESULT_SET, (ResultSet rs, int rowNum) -> {
                /*
                1. get actual instance of modelBase that is passed in
                2. get reference to the setters of the modelBase instance
                   or be able to pick out where to set things in the constructor
                3. loop thru ResultSet, setting parameters on model where the name of the
                   setter or constructor arg matches the name of the column in the resultSet
                */
            }).execute(sqlSource).get(RESULT_SET);
    }

}

The issues I have enumerated above at the things that I have not been able to figure out how I am supposed to do using the Reflection API in Java. Does anyone know how to do what I am trying to achieve?

Also, some of the values coming from the resultSet might not be Strings, but rather things like Dates and boolean. How would I reflectively call the right method on the resultSet? i.e. getInts() or getDate() or getBoolean(), etc.





Aucun commentaire:

Enregistrer un commentaire