我在REST API中使用了Hibernate
來完成數據庫工作。我基本上有3層;休眠:運行查詢以獲得日期範圍內的結果時沒有結果
- JSON服務層 - 這將處理JSON請求
- 服務層 - 這將處理至發送或從數據庫層
- 數據庫層所採取的數據的任何操作 - 與數據庫中運行。對於保存功能,更新等
請檢查下面的代碼
JSON服務層
@GET
@Path("/getByTimeRange/{fromDate}/{toDate}")
@Produces(MediaType.APPLICATION_JSON)
public List<Measurements> getByTimeRange(@PathParam("fromDate") String fromDate, @PathParam("toDate") String toDate)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
MeasurementsService measurementsService = new MeasurementsService();
List<Measurements> byTimeRange = null;
try {
byTimeRange = measurementsService.getByTimeRange(sdf.parse(fromDate), sdf.parse(toDate));
} catch (ParseException ex) {
Logger.getLogger(MeasurementsJSONService.class.getName()).log(Level.SEVERE, null, ex);
}
return byTimeRange;
}
服務層
public List<Measurements> getByTimeRange(Date fromDate, Date toDate)
{
Session session = measurementsDAOInterface.openCurrentSession();
Transaction transaction = null;
List<Measurements> byTimeRange = null;
try
{
transaction = measurementsDAOInterface.openTransaction(session);
byTimeRange = measurementsDAOInterface.getByTimeRange(fromDate, toDate, session);
transaction.commit();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
session.close();
}
return byTimeRange;
}
數據庫層
public List<Measurements> getByTimeRange(Date fromDate, Date toDate, Session session)
{
Query query = session.createQuery("FROM Units where last_updated BETWEEN :fromDate and :toDate");
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
List<Measurements> list = query.list();
System.out.println("Size "+list.size());
System.out.println("Dates "+toDate +" : "+ fromDate);
for(int i=0;i<list.size();i++)
{
System.out.println("Item: "+list.get(i).getLastUpdated());
}
return list;
}
所以基本上我所試圖做的是檢索數據集屬於一個特定的日期範圍 - 讓我們14-02-2016之間說14-09-2016。在Hibernate
,我用下面的代碼
FROM Units where last_updated BETWEEN :fromDate and :toDate
Units
是表和last_updated
是列名。
無論如何,我總是得不到任何結果,只是空白。即使數據庫層內的代碼System.out.println("Size "+list.size());
打印0
。
這裏有什麼問題?
謝謝你的回覆。 'ast_updated'是列名稱。在'單元'類中它是'lastUpdated'。無論如何,如果我以前的查詢使用了這些列名稱,我都會這麼做。 –
我想我找到了案例。我正在打電話到錯誤的桌子上!但讓我檢查一下。 –
是的,這是問題。表名稱不正確。非常感謝您提供支持。當您在'Units'表中特別詢問'last_updated'時,發現錯誤。來自我的+1。 –