Liferay的日期输入自定义查询

时间:2014-03-17 14:41:16

标签: java sql database liferay

我在使用日期输入执行自定义查询时遇到问题。 这是我的sql:

<sql
     id="MyEntityFinder.findByIns">
 <![CDATA[
     SELECT {EX_MyEntity.*}
     FROM EX_MyEntity
     WHERE
         (EX_MyEntity.myDate >= ? AND EX_MyEntity.myDate <= ?)
         ]]>
</sql>

这是我的发现者MyEntityFinderImpl:

public class MyEntityFinderImpl extends BasePersistenceImpl<MyEntity> implements MyEntityFinder{

    public static final String FIND_BY_INS = "MyEntityFinder.findByIns";
    public List<MyEntity> findByIns(Date from, Date to, int begin, int end) throws SystemException{
    Session session = null;
    try {
        session = openSession();
        String sql = CustomSQLUtil.get(FIND_BY_INS);
        SQLQuery q = session.createSQLQuery(sql);
        q.setCacheable(false);
        q.addEntity("EX_MyEntity", MyEntityImpl.class);
        QueryPos qPos = QueryPos.getInstance(q);  
        qPos.add("%"+from+"%");
        qPos.add("%"+to+"%");
        return (List<MyEntity>) QueryUtil.list(q, getDialect(), begin, end);
    } catch (Exception e) {
        throw new SystemException(e);
    } finally {
        closeSession(session);
    }
}    

}

以及我在jsp页面中如何调用它:

Calendar aMonthAgo = Calendar.getInstance();
aMonthAgo.set(Calendar.MONTH, aMonthAgo.get(Calendar.MONTH) - 1);
Calendar now = Calendar.getInstance();
List<MyEntity> monthly = MyEntityLocalServiceUtil.findByIns( 
                    new java.sql.Date(aMonthAgo.getTimeInMillis()),
        new java.sql.Date(now.getTimeInMillis()), 0,
        MyEntityLocalServiceUtil.getMyEntitysCount());

我得到&#34; java.sql.SQLException:数据异常:无效的日期时间格式&#34;在尝试执行查询时,我无法理解原因。

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

在jsp中: Timestamp timestamp = new Timestamp(aMonthAgo.getTimeInMillis());

在finder中: qPos.add(timestamp);

同样在sql查询中我会使用BETWEEN:

WHERE DATE(EX_MyEntity.myDate) BETWEEN ? AND ?