2012-06-29 74 views
-1

在我的表定義中,有一個int數據類型的列。如果值爲「0」,我希望jdbcTemplate更新方法默認情況下使用「NULL」而不是「0」來更新此字段。Spring JDBC模板更新問題

this.jdbcTemplate.update("UPDATE GCUR_OBSERVATION " 
       + "SET ObserverId = ?," + "ObservationDate = ?," 
       + "PointCuring = ?" 
       + " WHERE locationId = ? AND ObservationStatus = 0", 
       new Object[] { new Integer(newObservation.getObserverId()), 
         newObservation.getObservationDate(), 
         new Integer(newObservation.getLocationId()) }); 

上面的代碼段運行良好時Point Curingnot NULL。但是,如何將其作爲NULL存儲在數據庫表中?

回答

3

我希望你得到NUll指針異常。

試試這個

Integer locId = null; 

if(newObservation.getLocationId() != null) { 
locId = new Integer(newObservation.getLocationId()); 
if(locId == 0) { 
    locId = null; 
} 
} 

而現在經過此地LOCID。

this.jdbcTemplate.update("UPDATE GCUR_OBSERVATION " 
       + "SET ObserverId = ?," + "ObservationDate = ?," 
       + "PointCuring = ?" 
       + " WHERE locationId = ? AND ObservationStatus = 0", 
       new Object[] { new Integer(newObservation.getObserverId()), 
         newObservation.getObservationDate(), 
         locId) }); 
1

假設getLocationId()的返回類型是int,下面的代碼將工作。正確的解決方法是將getLocationId()的簽名更改爲Integer,並確保將其初始化的代碼將其設置爲NULL而不是0

this.jdbcTemplate.update("UPDATE GCUR_OBSERVATION " 
       + "SET ObserverId = ?," + "ObservationDate = ?," 
       + "PointCuring = ?" 
       + " WHERE locationId = ? AND ObservationStatus = 0", 
       new Object[] { new Integer(newObservation.getObserverId()), 
         newObservation.getObservationDate(), 
         newObservation.getLocationId() == 0 ? null : new Integer(newObservation.getLocationId()) });