在hibernate中是否有一种方法可以在一个字符串

时间:2016-11-21 02:53:05

标签: java sql postgresql hibernate

我在我的网络项目中使用了hibernate。我在String中执行createSQLQuery(queryString)这一行。以下是我在queryString中指定的值:

DROP TABLE monthlyevaluatedbudgettabletemp;
DROP TABLE monthlyadjustedbudgettabletemp;

CREATE TABLE monthlyevaluatedbudgettabletemp (budgetid bigint NOT NULL,
  approvedbudget numeric(19,2),
  april numeric(19,2),
  august numeric(19,2),
  budgetforyear bigint NOT NULL,
  december numeric(19,2),
  february numeric(19,2),
  january numeric(19,2),
  july numeric(19,2),
  june numeric(19,2),
  march numeric(19,2),
  may numeric(19,2),
  november numeric(19,2),
  october numeric(19,2),
  september numeric(19,2),
  branchid integer,
  accountid bigint,
  budgetlastyear bigint);

CREATE TABLE monthlyadjustedbudgettabletemp (adjustedid bigint NOT NULL,
  april numeric(19,2),
  august numeric(19,2),
  december numeric(19,2),
  february numeric(19,2),
  january numeric(19,2),
  july numeric(19,2),
  june numeric(19,2),
  march numeric(19,2),
  may numeric(19,2),
  november numeric(19,2),
  october numeric(19,2),
  september numeric(19,2),
  yeartodatemonth character varying(255),
  budgetid bigint);

INSERT INTO monthlyevaluatedbudgettabletemp SELECT * FROM monthlyevaluatedbudgettable where budgetforyear=2017;
INSERT INTO monthlyadjustedbudgettabletemp SELECT a.* from monthlyadjustedbudgettable as a join monthlyevaluatedbudgettable as e on a.budgetid=e.budgetid where e.budgetforyear = 2017

UPDATE monthlyevaluatedbudgettabletemp SET budgetforyear=2017,budgetlastyear=2016,april=0.00,approvedbudget=0.00,august=0.00,february=0.00,january=0.00,july=0.00,june=0.00,march=0.00,may=0.00,november=0.00,october=0.00,september=0.00,december=0.00;

UPDATE monthlyadjustedbudgettabletemp SET january=0.00,february=0.00,march=0.00,april=0.00,may=0.00,june=0.00,july=0.00,august=0.00,september=0.00,november=0.00,
october=0.00,december=0.00;

现在我用createSQLQuery(queryString).executeUpdate();运行它。我遇到了这种错误。

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

现在我的问题是,有没有办法可以在一个镜头中操纵查询。或者我必须将每个查询语句分开并逐个执行。就像我想在hibernate中执行.sql文件一样。

2 个答案:

答案 0 :(得分:2)

您无法在Hibernate中一次运行多个本机查询。

您必须将查询分开,然后单独运行它们。

这也是你在JDBC中如何做到的。

答案 1 :(得分:1)

所以我想出了这种代码与其他人分享。但我会查看@Pritam Banerjee的答案给我一个很好的答案。我split我的String by";"用于分隔每个语句的符号,我使用loop逐个执行它。

String[] splitQueryStr = queryString.split(";");
    for (String queryStr : splitQueryStr) {
        try {
            getSession().beginTransaction();
            getSession().createSQLQuery(queryStr).executeUpdate();
            getSession().getTransaction().commit();
        } catch (HibernateException he) {
            getSession().getTransaction().rollback();
            he.printStackTrace();
            throw new HibernateException("Hibernate Error");
        } catch (Exception e) {
            getSession().getTransaction().rollback();
            throw new Exception();
        } 
    }

它在我身上很好用。感谢您的评论和解答。欣赏它。