How to assign all matching properties from Groovy object to Java object?

后端 未结 2 449
夕颜
夕颜 2021-01-26 14:54

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

相关标签:
2条回答
  • 2021-01-26 15:08

    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 a List of GroovyRowResult objects (one per row). As this class is an instance of Map, groovy will use it to construct your java object automatically for you:

    class MyJavaClass {
      String property1, property2, property3
    }
    
    sql.rows("select property1, property2, property3 from temp_table").each { row ->
       MyJavaClass e = row
    }
    
    0 讨论(0)
  • 2021-01-26 15:20

    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

    • list filtered contains all property names that you intend to copy;
    • your table column names correspond to 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)})
    
    0 讨论(0)
提交回复
热议问题