草庐IT

Java hibernate org.hibernate.exception.SQLGrammarException : could not extract ResultSet on createSQLQuery

coder 2023-10-08 原文

我有这个方法。

private final void updateAllTableFields(final Class clazz){
    final String tableName = ((Table)clazz.getAnnotation(Table.class)).name();
    final String sqlQuery = new StringBuilder("SET @ids = NULL; ")
            .append("UPDATE ")
            .append(tableName)
            .append(' ')
            .append("set activeRecord=:activeRecord ")
            .append("where activeRecord=true and updateable=true ")
            .append("and (SELECT @ids \\:= CONCAT_WS(',', id, @ids)); ")
            .append("select @ids;")
            .toString();
    final Query query = session.createSQLQuery(sqlQuery)
            .setParameter("activeRecord",Boolean.FALSE);
    final Object idsList=query.uniqueResult();
    System.out.println("idsList = " + idsList);
}        

我想做一个更新并返回受影响的 IDs 这工作完美使用 rawSQL 以字符串方式返回 id 但我无法使用 Hibernate 任何提示使其工作!!!

在此先致谢并致以最诚挚的问候。

更新

我需要进行更新并返回受影响的 ID!!我不想进行简单的更新。

你可以check it out the original question here pal : https://stackoverflow.com/questions/44604763/java-hibernate-tips-about-update-all-table-fields-performance

更新 错误是

at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:89)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2065)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:909)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:353)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1873)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:311)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:141)
at org.hibernate.internal.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:966)
at company.nuevemil.code.finalizarEntornoDePrueba(Test.java:56)
at company.nuevemil.code.main(Test.java:27)


Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE student set activeRecord=false,uid=1 where activeRecord=true at line 1

最佳答案

you have to use HQL Query for bulk update. you are going write way only thing is that, you have to create HQL query for example


    Your Query Might be like this:-
    final String tableName = ((Table)clazz.getAnnotation(Table.class)).name();
        final String sqlQuery = new StringBuilder("SET @ids = NULL; ")
                .append("UPDATE ")
                .append(tableName)
                .append(' ')
                .append("set activeRecord=:activeRecord ")
                .append("where activeRecord=true and updateable=true ")
                .append("and (SELECT @ids \\:= CONCAT_WS(',', id, @ids)); ")
                .append("select @ids;")
                .toString();
        final Query query = session.createQuery(sqlQuery)
                .setParameter("activeRecord",Boolean.FALSE);
        final Object idsList=query.executeUpdate();

    Example Query:
    final String tableName = ((Table)clazz.getAnnotation(Table.class)).name();
       Query qry = session.createQuery("update "+tableName+" p set p.proName=?
    where p.productId=111");
                qry.setParameter(0,"updated..");
                int res = qry.executeUpdate();

关于Java hibernate org.hibernate.exception.SQLGrammarException : could not extract ResultSet on createSQLQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44641851/

有关Java hibernate org.hibernate.exception.SQLGrammarException : could not extract ResultSet on createSQLQuery的更多相关文章

  1. ruby-on-rails - Ruby 流量控制 : throw an exception, 返回 nil 还是让它失败? - 2

    我在思考流量控制的最佳实践。我应该走哪条路?1)不要检查任何东西并让程序失败(更清晰的代码,自然的错误消息):defself.fetch(feed_id)feed=Feed.find(feed_id)feed.fetchend2)通过返回nil静默失败(但是,“CleanCode”说,你永远不应该返回null):defself.fetch(feed_id)returnunlessfeed_idfeed=Feed.find(feed_id)returnunlessfeedfeed.fetchend3)抛出异常(因为不按id查找feed是异常的):defself.fetch(feed_id

  2. c - Ruby c 扩展 : How can I catch all exceptions, 包括不是 StandardErrors 的东西? - 2

    在ruby中,begin#...rescue#...end不会捕获不是StandardError子类的异常。在C中,rb_rescue(x,Qnil,y,Qnil);VALUEx(void){/*...*/returnQnil;}VALUEy(void){/*...*/returnQnil;}会做同样的事情。我如何从ruby​​C扩展中rescueException=>e(而不仅仅是rescue=>e)? 最佳答案 Ruby需要更多文档。我不得不进入ruby​​源代码,这是我发现的:VALUErb_rescue(VALUE(*b_p

  3. ruby-on-rails - 发生异常时发送电子邮件不起作用,使用 exception_notification - 2

    我正在从rails2.3迁移到rails3.1,我试图在生成异常时发送电子邮件。我正在使用exception_notificationgem。我的其余电子邮件都在工作。但是异常邮件不会被解雇。以下是我的staging.rb文件中的设置。config.action_mailer.perform_deliveries=trueconfig.action_mailer.raise_delivery_errors=true下面是application.rb中的代码C::Application.config.middleware.useExceptionNotification::Rack,:e

  4. ruby-on-rails - 有可能 CanCan can :manage, :all except one or more method? - 2

    我在做:can:manage,:allifuser.role=='admin'can:approve,Anunciodo|anuncio|anuncio.try(:aprovado)==falseend我的第二种方法不起作用,因为:manage:all覆盖了它。有一种方法可以声明可以管理除批准之外的所有内容吗?在里面批准我只是做can:approve,Anunciodo|anuncio|user.role=='admin'&&anuncio.try(:aprovado)==falseend什么是更好的解决方案? 最佳答案 尝试换一种

  5. ruby-on-rails - Rails 和 attr_accessible : is there a way to raise an exception if a non-mass-assignable attribute is mass-assigned? - 2

    如果尝试批量分配attr_accessible不允许的属性,是否有办法让Rails引发错误?这在开发中会很方便,可以提醒我为什么我Shiny的新模型不起作用,也有助于登录生产环境以检测恶意事件。我正在使用Rails2.3.8,但可能很快就会迁移到3。 最佳答案 从Rails3.2开始,这不再需要monkeypatching——rails现在提供了这种行为。将其放入development.rb和test.rb:config.active_record.mass_assignment_sanitizer=:strict

  6. ruby-on-rails - Ruby无一异常(exception)地获得回溯 - 2

    我有一个RubyonRails应用程序,其中一个模型的验证失败。对于此验证可能失败的地方,代码库有不同的入口点。我有兴趣弄清楚它是从哪里来的。由于这是一个简单的验证方法,因此不涉及任何异常,我只是从方法中返回false并且保存失败。目前是否还可以记录回溯以查明此验证源自哪个服务/路由,以便我可以查看是什么导致此对象的状态发生更改以使其验证失败? 最佳答案 你可以试试caller():deffoo2putscallerenddeffoofoo2#line5endfoo#line7结果:test.rb:5:in`foo'test.rb:

  7. ruby - Rspec any_instance.stub 为 nil :NilClass exception 引发未定义的方法 `any_instance_recorder_for' - 2

    这是我正在测试的包含在Foo.rb中的类:classFoodefbarreturn2endend这是Foo_spec.rb中包含的我的测试:require"./Foo.rb"describe"Foo"dobefore(:all)doputs"#{Foo==nil}"Foo.any_instance.stub(:bar).and_return(1)endit"shouldpassthis"dof=Foo.newf.bar.shouldeq1endend我得到以下输出:falseFFailures:1)FooShouldpassthisFailure/Error:Foo.any_insta

  8. ruby - 公寓 ruby gem : Want to Catch an exception - 2

    我正在使用这个apartmentruby。我在application.rb文件中添加了这个:config.middleware.use'Apartment::Elevators::Subdomain'当我尝试在PostgreSQL中不存在子域“test”模式的浏览器url“test.domain.local:3000”中点击这个时,我看到了这个错误Apartment::SchemaNotFound(Oneofthefollowingschema(s)isinvalid:test,"public")我知道这是gem的正常行为,但想捕获此异常并将用户重定向到其他页面,我该怎么做?

  9. ruby - 如何通过正则表达式查找括号内的文本,但有一些异常(exception)? - 2

    我有一个正则表达式/^\[(text:\s*.+?\s*)\]/mi目前可以捕获以text开头的括号中的文本:。以下是它的工作示例:[text:hereismytextthatiscapturedwithinthebrackets.]现在,我想添加一个异常(exception),以便它允许某些括号,如下例所示:[text:hereismytextthatiscapturedwithinthebracketsandalsoinclude![](/some/path)]基本上,我需要它允许匹配中的![](/some/path)括号。如有任何帮助,我们将不胜感激。谢谢。更新:下面是括号内的文

  10. ruby-on-rails - 之前(:each) for all tests except one - 2

    这是我的spec_helper.rb的一部分:RSpec.configuredo|config|config.before(:each)dologin(email,password)visitroot_urlendend我在所有(20多个)测试中都需要,除了一个。有没有办法避免单一测试执行beforehook? 最佳答案 您可以将元数据添加到不需要登录的测试中,然后在您的beforeHook中评估该元数据。例如,同一个文件中的两个测试。一个需要登录,一个不需要。#foo_spec.rbdescribeFoododescribe"#b

随机推荐