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?
Som
Some groovy magic helps:
def filtered = ['property1', 'property2', ....]
sql.eachRow("select * from temp_table") {
def e = new MyJavaClass(it.properties.findAll{filtered.contains(it.key)})
}
Given that
filtered
contains all property names that you intend to copy;MyJavaClass
declared property names (the same as in the list filtered
);MyJavaClass
has both default (empty) constructor and constructor
that takes all properties as parameters;MyJavaClass
declares public setters for properties;E.g:
public MyJavaClass() {}
public MyJavaClass(String property1, String property2, ....) {
this.property1 = property1;
this.property2 = property2;
.... }
public void setProperty1(String property1) {this.property1 = property1;}
public void setProperty2(String property2) {this.property2 = property2;}
....
You may use filtered
as a list of undesired properties like this:
def filtered = ['class', 'metaClass', ....]
then:
def e = new MyJavaClass(it.properties.findAll{!filtered.contains(it.key)})