We wrote something like this at work:

ResultSetTransformer is an interface with a single method:

public Object instanceFromRow(java.sql.ResultSet rset) throws java.lang.Exception;

We mostly use a single implementation of the interface which we call "SimplePropertyMappedTransformer" You set the bean class when you construct the SPMT, and then for each call to instanceFromRow, it creates a new instance of the bean class and calls the following:


protected void populateBean(Object bean, ResultSet rset)
throws java.lang.IllegalAccessException,
java.lang.reflect.InvocationTargetException, java.sql.SQLException {


        Map               properties = new HashMap();
        ResultSetMetaData metaData   = rset.getMetaData();
        int               cols       = metaData.getColumnCount();

        for (int i = 1; i <= cols; i++) {
            String value = rset.getString(i);

            if (value == null) {
                value = "";
            }

log.debug("property: " + metaData.getColumnName(i) + ", value: " + value);
properties.put(metaData.getColumnName(i), value);
}


        BeanUtils.populate(bean, properties);
    }

This assumes that you can alias the column names in your SQL to property names. This works fine in Oracle, but I'm not very expert on the differences between ANSI SQL and Oracle SQL. If you had to, you make a version which also takes a Properties which mapped column names to bean property name.

Then we have another layer which takes a SQL string and a ResultSetTransformer and is responsible for managing the connection, executing the query, and iterating through the result set, building a list from calls to the RST...

Hope that helps...

Joe




Matt Raible wrote:
Dear Struts Experts,

I recently started a new project where most of the backend code is already
written with JDBC and ResultSets.  The ResultSets are iterated through and a
POJOs values are set using pojo.setName(rs.getString("...")), etc. - you get
the point.  I'm wondering if there's an easier way - so I could do something
like this:

ResultSet rs = stmt.executeQuery("SELECT ...");
List objects = FancyUtilitity.convertResultSetToListOfObjects(rs,
object.class);

Hibernate let me do this very simply - and I miss the fact that I could type
a line or two to get a List of POJOs.
  List users = ses.createQuery("from u in class " + User.class
                               + "order by u.name").list();


--
--
Joe Germuska [EMAIL PROTECTED] http://blog.germuska.com "If nature worked that way, the universe would crash all the time." --Jaron Lanier


---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]



Reply via email to