Hibernate executeUpdate不删除行

时间:2013-10-22 17:07:33

标签: hibernate

我想在同一个会话中执行几个SELECT和DELETE,但是DELETE返回没有删除任何行,为什么呢?感谢

痕迹: - 历史记录清除:通过查询删除的10个条目 - 自2013-10-14 13:07:28.0:0条目清除以来被查询删除

源代码:

@Override
public void removeAllHistoryOlderThan(Date since) {
    try
    {
        int deletedEntities = 0;
        int nbRetries = 0;

        Session session = getHibernateTemplate().getSessionFactory().openSession();
        Query query = session.createQuery("SELECT h FROM History h WHERE h.operationDate < :since ORDER BY  h.operationDate ASC").setDate("since", since).setMaxResults(10);            
        List list = query.list();

        while ( (list.size() != 0)
            &&  (nbRetries < 20))
        {
            logger.info("History purge : " + list.size() + " entries to remove by query");

            Transaction tx = session.beginTransaction();
            Date maxSince = ((History)list.get(list.size()-1)).getOperationDate(); 
            int tmpDeletedEntities = session.createQuery("DELETE History h WHERE h.operationDate < :since")
                                            .setDate("since", maxSince)
                                            .executeUpdate();
            tx.commit();

            logger.info("History purge since " + maxSince + " : " + tmpDeletedEntities + " entries removed by query");
            deletedEntities += tmpDeletedEntities;
            nbRetries++;

            list = query.list();
        }
        session.close();
        logger.info("History purge since " + since + " : Total = " + deletedEntities + " entries removed");
    }
    catch (HibernateException e)
    {
        logger.error(e.getMessage());
    }
}

1 个答案:

答案 0 :(得分:0)

函数“setDate”截断参数maxSince,我使用“setTimStamp”更改了我的查询

int tmpDeletedEntities = session.createQuery("DELETE History h WHERE h.operationDate < :since")
.setTimestamp("since", maxSince)
.executeUpdate();