你可以在Java中的hibernate SQL(HQL)中使用ALTER和AUTO_INCREMENT吗?

时间:2016-09-15 11:45:51

标签: java hibernate hql

我一直在网上冲浪,无法找到我特定问题的答案。我正在使用Struts 1.x和Hibernate SQL来运行我的SQL查询。我遇到的问题是:

Session ses = factory.getCurrentSession();
ses.createSQLQuery("ALTER TABLE ZeeCallSp AUTO_INCREMENT = :id").setParameter("id", 1).executeUpdate();

这给了我这个错误:

org.hibernate.exception.GenericJDBCException: could not execute native bulk manipulation query

我尝试了不同的方法,但仍然会遇到同样的错误:

String hql = "ALTER TABLE ZeeCallSp AUTO_INCREMENT = 1";
SQLQuery sqlQuery = ses.createSQLQuery(hql);
sqlQuery.executeUpdate();

另一个:

String hql = "ALTER TABLE ZeeCallSp AUTO_INCREMENT = :id";
Query query = ses.createQuery(hql);
query.setInteger("id", 1);
query.executeUpdate();

所以我需要做的是,在删除表格中的所有记录后,将自动增量值重置为1。

这样做的正确方法是什么?

编辑:

我首先通过运行它(完美地运行)删除表中的记录:

public void deleteAllRecordsInTableZeeCallSp() {
    try {
        Session ses = factory.getCurrentSession();
        ses.createQuery("delete from ZeeCallSp").executeUpdate();
    }
    catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new EJBException("Could not delete record.");
    }
}

然后就在那之后,我正在运行这个让我无法执行本机批量操作...在query.executeUpdate()时出错;

public void resetAutoIncrementForTableZeeCallSp() {
    try {
        Session ses = factory.getCurrentSession();

        Transaction tx=ses.beginTransaction();      

        Query query=ses.createSQLQuery("ALTER TABLE ZeeCallSp AUTO_INCREMENT = 1");
        query.executeUpdate();  //could not execute native bulk manipulation        

        tx.commit();

    }
    catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new EJBException("Could not delete record.");
    }
}   

此致

2 个答案:

答案 0 :(得分:0)

在我看来,这不是正常的操作。 有信息原因:

https://stackoverflow.com/a/12008019/6834892

如果删除所有记录,则此序列应继续递增。

答案 1 :(得分:0)

首先,您应该删除表格中的所有记录' ZeeCallSp'。 稍后,使用以下代码

import org.hibernate.Query;

Transaction tx=session.beginTransaction();

Query query=session.createSQLQuery("ALTER TABLE ZeeCallSp AUTO_INCREMENT = 1");
query.executeUpdate();
tx.commit();
session.close();

然后插入一些记录,它应该可以正常工作!

更新代码:删除操作尚未完成,直到您提交交易为止。

public void deleteAllRecordsInTableZeeCallSp() {
try {

    Session ses = factory.getCurrentSession();
    Transaction tx=ses.beginTransaction();
    ses.createQuery("delete from ZeeCallSp").executeUpdate();
    tx.commit(); 
    ses.close();      
}
catch (Exception e) {
    log.error(e.getMessage(), e);
    throw new EJBException("Could not delete record.");
}
}