【发布时间】:2017-04-29 19:38:48
【问题描述】:
我在我的 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。
这里有什么问题?
【问题讨论】:
标签: java mysql json hibernate rest