public List getTime(DeviceHistory beTime,DeviceHistory endTime)throws Exception {List l=new ArrayList();Session s = this.getSession();Query q=s.createQuery("from DeviceHistory d where d.DId=:dd and d.deviceTime between :aa and :bb");q.setDate("aa", beTime.getDeviceTime());q.setDate("bb", endTime.getDeviceTime());l=q.list();s.close();return l;}public static void main(String[] args) throws Exception{List l= new ArrayList();DeviceHistoryDao dgd=new DeviceHistoryDao();ToChange tc=new ToChange();DeviceHistory dg=new DeviceHistory();dg.setDId(1);// dg.setId(6);dg.setDeviceTime(tc.charToDate("2008-10-06 13:00"));DeviceHistory dg1=new DeviceHistory();dg1.setDId(1);// dg1.setId(8);dg1.setDeviceTime(tc.charToDate("2008-10-06 16:00"));l=dgd.getTime(dg,dg1);System.out.println("list=="+l.size());}public Date charToDate(String s){DateFormat df=new SimpleDateFormat("yyyy-mm-dd hh:mm");Date dd=new Date(0);try {if(s!=null&&s.trim().length()>0){dd = (Date) df.parse(s);}} catch (Exception e) {e.printStackTrace();}return dd;}public class DeviceHistory {// Fields private Integer id;private Integer DId;private String lng;private String lat;private Float speed;private String info;private Date deviceTime;}beTime.getDeviceTime()獲取的是java.util.Date;類型,在public List getTime(DeviceHistory beTime,DeviceHistory endTime)方法里我少了 q.setInteger("dd", beTime.getDId());這里是我粘貼的時候沒有粘上去。
2 回答

Helenr
TA貢獻1780條經驗 獲得超4個贊
hibernate
mysql
查詢日期范圍:
呵呵,有必要你在這里用SimpleDateFormat轉化日期格式嗎?
用mysql的TO_DAYS函數就可以了,如下:
from
DeviceHistory
d
where
d.DId=:dd
and
where
TO_DAYS(d.deviceTime)
>=
TO_DAYS("+beginTime+")
and
TO_DAYS(d.deviceTime)
<=
TO_DAYS("+endTime+")
試試吧,beginTime和endTime就是日期范圍
mysql的TO_DAYS函數返回的就是天數,你就不要轉化日期格式了

溫溫醬
TA貢獻1752條經驗 獲得超4個贊
hibernate mysql 查詢日期范圍:
呵呵,有必要你在這里用SimpleDateFormat轉化日期格式嗎?
用mysql的TO_DAYS函數就可以了,如下:
from DeviceHistory d where d.DId=:dd and where TO_DAYS(d.deviceTime) >= TO_DAYS("+beginTime+") and TO_DAYS(d.deviceTime) <= TO_DAYS("+endTime+")
試試吧,beginTime和endTime就是日期范圍
mysql的TO_DAYS函數返回的就是天數,你就不要轉化日期格式了
添加回答
舉報
0/150
提交
取消