Skip to content
Advertisement

JDBCTemplate set nested POJO with BeanPropertyRowMapper

Given the following example POJO’s: (Assume Getters and Setters for all properties)

JavaScript

One can easily query a database (postgres in my case) and populate a list of Message classes using a BeanPropertyRowMapper where the db field matched the property in the POJO: (Assume the DB tables have corresponding fields to the POJO properties).

JavaScript

I’m wondering – is there a convenient way to construct a single query and / or create a row mapper in such a way to also populate the properties of the inner ‘user’ POJO within the message.

That is, Some syntatical magic where each result row in the query:

JavaScript

Produce a list of Message with the associated User populated


Use Case:

Ultimately, the classes are passed back as a serialised object from a Spring Controller, the classes are nested so that the resulting JSON / XML has a decent structure.

At the moment, this situation is resolved by executing two queries and manually setting the user property of each message in a loop. Useable, but I imagine a more elegant way should be possible.


Update : Solution Used –

Kudos to @Will Keeling for inspiration for the answer with use of the custom row mapper – My solution adds the addition of bean property maps in order to automate the field assignments.

The caveat is structuring the query so that the relevant table names are prefixed (however there is no standard convention to do this so the query is built programatically):

JavaScript

The custom row mapper then creates several bean maps and sets their properties based on the prefix of the column: (using meta data to get the column name).

JavaScript

Again, this might seem like overkill for a two class join but the IRL use case involves multiple tables with tens of fields.

Advertisement

Answer

Spring introduced a new AutoGrowNestedPaths property into the BeanMapper interface.

As long as the SQL query formats the column names with a . separator (as before) then the Row mapper will automatically target inner objects.

With this, I created a new generic row mapper as follows:

QUERY:

JavaScript

ROW MAPPER:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement