2011-07-26 24 views
1

我想通過SQL調用加載一組對象。 SQL查詢返回比所需更多的屬性。除了糾正SQL查詢。如何在產品申報時忽略所有多餘的參數?處理比所需更多的屬性

import groovy.sql.Sql 

class Product { 
    Integer id; 
    Integer type; 
    String unique; 
} 

def var = []; 
sql = Sql.newInstance("jdbc:jtds:sqlserver://localhost/[DB]", "user", "password","net.sourceforge.jtds.jdbc.Driver"); 
sql.eachRow("select * from Products", { var << new Product(it.toRowResult()) }); 

,我發現了異常:

groovy.lang.MissingPropertyException: No such property: [other fields from the SQL result] 

回答

1

默認Groovy的行爲是拋出一個groovy.lang.MissingPropertyException每當你嘗試將值設置爲不bean中存在的屬性。我不太確定你是否可以改變這種行爲。但是,您可以編寫一個幫助器方法來過濾掉不存在的屬性。

def filterResult(bean, row) { 
    def filteredProps = [:] 

    row.each { key, value -> 
     if(bean.metaClass.properties.find { prop -> prop.name == key }) { 
      filteredProps.put(key, value) 
     } 
    } 

    filteredProps 
} 

def var = [] 

sql.eachRow("select * from Products", { 
    var << new Product(filterResult(Product, it.toRowResult())) 
}) 
+0

這當然有道理。但我想象這些屬性存儲在一個哈希映射中[而不是直接的1對1綁定]。所以額外的屬性會導致問題對我來說沒有意義。我錯了嗎?如果你沒有完成所有的屬性,Groovy就不會抱怨,只要你有足夠的信息。 – monksy

+0

默認情況下,Groovy確實將地圖條目綁定到類中的屬性中。所以額外的鍵將導致groovy.lang.MissingPropertyException。如果您覆蓋產品(地圖),您可以更改此行爲。 –