2

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.

cirko
  • 211
  • 2
  • 13

1 Answers1

2

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.

vanOekel
  • 6,358
  • 1
  • 21
  • 56
  • thanks! I just thought that if "columnname = parametername" for a POJO class works one way with the `ResultSetHandler` class that it shouldn't be too difficult to have just the same thing for the other way round... it's just not "sexy" to hardcode it... but then again you mentioned all the SQL possibilities one would have to think about... well let's hardcode it then :) – cirko Oct 24 '15 at 16:36
  • BTW that model binding is nice, that'll do it for my skill level! – cirko Oct 24 '15 at 16:55