让应用程序具有将日期列设置为唯一的表。设置唯一,以便表中每天始终只有一条记录。
以下代码在白天第x次运行时更新表中的信息:
else{
StringBuilder query = new StringBuilder("from Weather where COLUMN_DATE = '" + weatherData.getDate() + "'");
List weatherDat = session.createQuery(query.toString()).list();
if (weatherDat.size()>0) {
Weather curWeather = (Weather) weatherDat.get(0);
curWeather.setWeatherId(weatherData.getWeatherId());
curWeather.setDescription(weatherData.getDescription());
curWeather.setHumidity(weatherData.getHumidity());
curWeather.setPressure(weatherData.getPressure());
curWeather.setTemperature(weatherData.getTemperature());
curWeather.setWindDirection(weatherData.getWindDirection());
curWeather.setWindSpeed(weatherData.getWindSpeed());
}
else之前的代码检查表中当天的现有记录,而weatherData是包含收集数据的对象。是否有更好,更简洁的方式来更新每日记录?
答案 0 :(得分:0)
使用uniqueResult而不是list
在这里查看uniqueResult()方法:https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html#uniqueResult%28%29
然后您可以执行以下操作:
Weather curWeather = (Weather) session.createQuery(query.toString()).uniqueResult();
旁注
信任weatherData.getDate()容易受到SQL注入攻击。而是使用命名查询参数。这些是形式的标记:查询字符串中的名称。通过调用
session.createQuery("from Weather where COLUMN_DATE = :weatherDate")
.setParameter("weatherDate", weatherData.getDate());