您好我试图使用基于开始和结束日期的Hibernate来获取表中的行数但是我得到的不是有效月错误
Session session = sessionFactory.getCurrentSession();
startDate = "13-02-02 00:00:00";
endDate = "17-02-02 00:00:00";
try{
String hql = "select Count(*) from mytable where PERIOD_START_DATETIME between '"
+ startDate + "' AND '" + endDate + "'";
Query query = session.createQuery(hql);
long count=(long) query.uniqueResult();
return count;
} finally{
session.close();
}
这是我的表格描述
Name NULL TYPE NAME NOT NULL VARCHAR2(255 CHAR) PERIOD_END_DATETIME NOT NULL TIMESTAMP(6) PERIOD_START_DATETIME NOT NULL TIMESTAMP(6) PROD_OFFER_TERM_TYPE_ID NOT NULL NUMBER(19)
答案 0 :(得分:3)
使用字符串连接生成SQL查询通常是个坏主意,因为
HQL支持绑定变量/预处理语句,因此这应该有效:
String hql = "select Count(*) from mytable where PERIOD_START_DATETIME between :startdate AND :enddate ";
Query query = session.createQuery(hql);
query.setParameter("startdate", startDate);
query.setParameter("enddate", endDate);
(其中startDate和endDate是实际的java.sql.Timestamp
值,而不是字符串)。
答案 1 :(得分:2)
由于数据库中的开始/结束时间是SQL TIMESTAMP
,您可以将Timestamp
对象传入查询,如下所示:
Session session = sessionFactory.getCurrentSession();
final DateFormat df = new SimpleDateFormat("yy-MM-dd");
// omitting the time part will set the time to midnight (00:00:00)
Timestamp start = new Timestamp(df.parse("13-02-02").getTime());
Timestamp end = new Timestamp(df.parse("17-02-02").getTime());
try {
String hql =
"select Count(*) from mytable where PERIOD_START_DATETIME between ? AND ?";
Query query = session.createQuery(hql)
.setTimestamp(0, start)
.setTimestamp(1, end);
long count = (long) query.uniqueResult();
return count;
} finally {
session.close();
}
答案 2 :(得分:1)
确保您确实在查询中传递了日期值。 您可以使用to_date函数指定日期的格式,因为它在字符串中表示。
select Count(*)
from mytable
where PERIOD_START_DATETIME between to_date(startDate,'DD-MM-YYYY HH24:MI:SS') AND to_date(endDate,'DD-MM-YYYY HH24:MI:SS');
答案 3 :(得分:0)
select Count(*)
from mytable
where PERIOD_START_DATETIME between TO_TIMESTAMP(:startDate, 'YY-MM-DD HH24:MI:SS') AND TO_TIMESTAMP(:endDate, 'YY-MM-DD HH24:MI:SS')