在oracle 10g数据库中有 test 表,表中有一个字段是 testTime  Date类型,里面有数据
2007-10-29 10:50:51和2007-10-30 13:34:41一共两条。
第一种方法:Hql语句
select count(*) from Test as t
where TO_CHAR(t.testTime,'YYYY-MM-DD')>= '2007-10-29'
where TO_CHAR(t.testTime,'YYYY-MM-DD')<= '2007-10-30'
有两条数据。第二种方法:
session = HibernateSessionFactory.getSession();
DetachedCriteria dCrit = DetachedCriteria.forClass(Test.class);
dCrit.add(Restrictions.le("testTime","2007-10-30");
dCrit.add(Restrictions.ge("testTime","2007-10-29");
只有2007-10-29 10:50:51检索出了。问题:如果我想让两种形式都检索出两条记录,第二种方法应该怎么样修改?产生正要的结果原因是什么?

解决方案 »

  1.   

    第一种方法:Hql语句 
    select count(*) from Test as t 
    where TO_CHAR(t.testTime, 'YYYY-MM-DD ') >=  '2007-10-29 ' 
    where TO_CHAR(t.testTime, 'YYYY-MM-DD ') <=  '2007-10-30 '第一种方法对
      

  2.   

    我用的是hibernate3.0,实现代码如下: String start_str="2007-10-29 00:00";
     String end_str="2007-10-30 23:59";
     SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
     Date start_date=null,end_date=null; try {
     start_date= sdf.parse(start_str);
             end_date= sdf.parse(end_str);
     } 
     catch (ParseException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
      } 
     
    try{  
     Session session=HibernateSessionFactory.currentSession();
     Transaction tran=session.beginTransaction();
     Criteria criteria=session.createCriteria(Test.class); Criterion criterion=Expression.between("testTime",start_date,end_date); List lst=criteria.list();
     tran.commit();

     }
     catch(Exception ex){ex.getMessage();
       System.out.println(ex.getMessage());
    }
     finally{
      //无论是否加载成功,Session对象都要被关闭
     HibernateSessionFactory.closeSession();
     }
     return lst;lst 返回结果就是所要得到的两条数据,抛砖引玉,望后来者高见.
     
      

  3.   

    session = HibernateSessionFactory.getSession(); 
    DetachedCriteria dCrit = DetachedCriteria.forClass(Test.class); 
    dCrit.add(Restrictions.le("testTime","2007-10-30"); 
    dCrit.add(Restrictions.ge("testTime","2007-10-29"); 
    代码时简写的实际上是
    session = HibernateSessionFactory.getSession(); 
    DetachedCriteria dCrit = DetachedCriteria.forClass(Test.class); 
    dCrit.add(Restrictions.le("testTime",Date.valueOf("2007-10-29")));
    dCrit.add(Restrictions.ge("testTime",Date.valueOf("2007-10-29")));问题我自己解决了,不过方法我觉得不好,谁有好的方法告诉我??
      

  4.   

    我来告诉你原因吧:le 是小于等于,dCrit.add(Restrictions.le("testTime","2007-10-30");   你的这段代码是小于等于2007-10-30 00 点,明白我的意思了吗,就是说,默认小于等于的是零点,你如果想查30号的数据,你需要在30号的基础上加一天
    ,查出来就有30号的数据了