I want to use Groovy with JDBC to load some data from a table. I then want to copy the properties across where the property names match. How can I do this in Groovy?
Something like this:
sql.eachRow("select * from temp_table") {
def e = new MyJavaClass()
// copy matching fields from it to e
}
Some groovy magic helps:
Given that
filtered
contains all property names that you intend to copy;MyJavaClass
declared property names (the same as in the listfiltered
);MyJavaClass
has both default (empty) constructor and constructor that takes all properties as parameters;MyJavaClass
declares public setters for properties;E.g:
You may use
filtered
as a list of undesired properties like this:then:
In addition to topchef's answer, you might be able to use some groovy map magic
If you limit your sql to the properties in your Java Class (and assuming you can hold the entire result in memory at once), then you should be able to use the
rows
method to get aList
ofGroovyRowResult
objects (one per row). As this class is an instance ofMap
, groovy will use it to construct your java object automatically for you: