javamysqlapache-commons-dbutils

Can apache-commons-dbutils covert beans to an SQL statement?


As a newbie to Servlet programming, I think I may not have gotten something right here: I understand the concept of Java Beans and little ORM helper classes like org.apache.commons.dbutils.DbUtils. I can convert a ResultSet into an instance of my JavaBean-object with a ResultSetHandler and a BeanHandler. But isn't there any convenient way to do it the other way round, other than hardcoding the SQL string? Something like

QueryRunner run = new QueryRunner(datasource);
int result = run.update("UPDATE " + tableName + " SET " + [and now some Handler sets all the columns from the JavaBean]);

At least, I didn't find anything like that! Or did I get it wrong? Help appreciated.


Solution

  • You did not get it wrong, you will still need a hard-coded SQL string as shown in this answer. Sql2o also requires a hard-coded SQL string but it will let you bind a POJO which gets you half-way there, see here (bottom of the page).

    I think you will always need a hard-coded SQL string of some form because these are JDBC helper libraries and not "object relational mappers". Before the insert is done it is not known which properties are auto-generated, have a default-value, are foreign keys, allow null-values, etc.. All this information is required to prepare a proper insert statement based on a POJO/JavaBean and that goes beyond the scope of the helper libraries. On the plus-side: specifying a SQL string is explicit (there is no magic behind the scenes) and keeps you in full control.