Sqlgrammarexception error performing isolated work

introduction
The

error is simple, but make a note of it and help someone who needs help

background programming today, suddenly reported an error, the complete error message is as follows: </p b>

org.springframework.dao.InvalidDataAccessResourceUsageException: error performing isolated work; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: error performing isolated work

	at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:279)
	at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253)
	at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
	at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
	at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
	at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
	at com.sun.proxy.$Proxy99.save(Unknown Source)
	at com.imooc.repository.ProductCategoryRepositoryTest.saveTest(ProductCategoryRepositoryTest.java:36)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
	at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
	at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
	at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
	at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.hibernate.exception.SQLGrammarException: error performing isolated work
	at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
	at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
	at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
	at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
	at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:79)
	at org.hibernate.id.enhanced.TableStructure$1.getNextValue(TableStructure.java:125)
	at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
	at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:482)
	at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123)
	at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:192)
	at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:135)
	at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:62)
	at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:800)
	at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:785)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:308)
	at com.sun.proxy.$Proxy93.persist(Unknown Source)
	at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:489)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359)
	at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)
	at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608)
	at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)
	at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
	at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
	... 40 more
Caused by: java.sql.SQLSyntaxErrorException: Table 'sell.hibernate_sequence' doesn't exist
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
	at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
	at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:974)
	at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1024)
	at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
	at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
	at org.hibernate.id.enhanced.TableStructure.executeQuery(TableStructure.java:216)
	at org.hibernate.id.enhanced.TableStructure.access$300(TableStructure.java:46)
	at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:138)
	at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:126)
	at org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:55)
	at org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:34)
	at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:57)
	... 74 more

solution 1:

as you can see from the error message, when inserting data, you need to check the table structure fields to see which fields are missing </p b>

Read More:

Содержание

  1. JBossDeveloper
  2. issue when creating new person #14
  3. Comments
  4. Error performing isolated work
  5. Русские Блоги
  6. О jpa org.springframework.dao.springdataaccessresourceusageexception: Solutions Excession: решение
  7. Интеллектуальная рекомендация
  8. IView CDN Загрузка значка шрифта нормальная, а значок шрифта не может быть загружен при локальной загрузке JS и CSS
  9. Критическое: ошибка настройки прослушивателя приложения класса org.springframework.web.context.ContextLoaderLis
  10. 1086 Не скажу (15 баллов)
  11. Pandas применяют параллельный процесс приложения, многоядерная скорость очистки данных
  12. PureMVC Learning (Tucao) Примечания
  13. Русские Блоги
  14. Различные аномальные ямы, возникающие при использовании Hibernate
  15. Предисловие
  16. Интегрированная среда
  17. Исключение первое
  18. Аномалия вторая
  19. Исключение третье

JBossDeveloper

We are in process of upgrading to 7.1 from 4.2.3a. During this excersize I did few changes to my hibernate.cfg.xml. Attached hibernate.cfg.xml

As well as here is standalone.xml entries:

And I am getting following error:

12:00:26,470 WARN [org.hibernate.util.JDBCExceptionReporter] (http—127.0.0.1-8080-2) SQL Error: 0, SQLState: null

12:00:26,471 ERROR [org.hibernate.util.JDBCExceptionReporter] (http—127.0.0.1-8080-2) You cannot commit during a managed transaction!

12:00:26,472 ERROR [yyy_common.yyyUserActivityException] (http—127.0.0.1-8080-2) [yyyUserActivity][yyyUserActivityException][myBean][createConnection] Failed to create connection: org.hibernate.exception.GenericJDBCException: error performing isolated work

at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103) [hibernate3.jar:3.2.6.ga]

at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91) [hibernate3.jar:3.2.6.ga]

at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) [hibernate3.jar:3.2.6.ga]

at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29) [hibernate3.jar:3.2.6.ga]

at org.hibernate.engine.transaction.Isolater$JdbcDelegate.delegateWork(Isolater.java:207) [hibernate3.jar:3.2.6.ga]

at org.hibernate.engine.transaction.Isolater.doIsolatedWork(Isolater.java:43) [hibernate3.jar:3.2.6.ga]

at org.hibernate.engine.TransactionHelper.doWorkInNewTransaction(TransactionHelper.java:51) [hibernate3.jar:3.2.6.ga]

at org.hibernate.id.TableGenerator.generate(TableGenerator.java:94) [hibernate3.jar:3.2.6.ga]

Attached full log. Any pointer would be really appreciated.

Источник

issue when creating new person #14

for example when the birthday is 11/11/88 very strange

org.springframework.dao.InvalidDataAccessResourceUsageException: error performing isolated work; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: error performing isolated work at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:240)

[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:223)

[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)

[spring-orm-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)

[spring-tx-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)

[spring-tx-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)

[spring-tx-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)

[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135)

[spring-data-jpa-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)

[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)

[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)

[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)

[spring-data-commons-2.0.10.RELEASE.jar:2.0.10.RELEASE] at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)

[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)

[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE] at com.sun.proxy.$Proxy112.save(Unknown Source)

[na:na] at crud.vaadin.PersonForm.lambda$new$da1cf436$1(PersonForm.java:41)

The text was updated successfully, but these errors were encountered:

Источник

Error performing isolated work

Hibernate version: 3.2 RC3

Full stack trace of any exception that occurs:
Caused by: java.rmi.RemoteException: ; nested exception is:
org.hibernate.HibernateException: error performing isolated work
at org.hibernate.engine.transaction.Isolater$JtaDelegate.delegateWork(Isolater.java:142)
at org.hibernate.engine.transaction.Isolater.doIsolatedWork(Isolater.java:40)
at org.hibernate.engine.TransactionHelper.doWorkInNewTransaction(TransactionHelper.java:51)
at com.generali.ruby.utils.persistance.RubyPIDGenerator.generate(RubyPIDGenerator.java:146)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:98)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
at com.generali.ruby.bo.BusinessObject.save(BusinessObject.java:67)
at com.generali.ruby.workflow.BusinessProcessManager.createBusinessProcess(BusinessProcessManager.java:202)
at com.generali.ruby.services.workflow.WorkflowFacadeBean.createBusinessProcess(WorkflowFacadeBean.java:128)
at com.generali.ruby.services.workflow.EJSRemoteStatelessWorkflowFacade_e9815e81.createBusinessProcess(EJSRemoteStatelessWorkflowFacade_e9815e81.java:175)
at com.generali.ruby.services.workflow._WorkflowFacade_Stub.createBusinessProcess(_WorkflowFacade_Stub.java:309)
. 39 more
Caused by: org.hibernate.HibernateException: error performing isolated work
. 57 more

Name and version of the database you are using: DB2 V 7.2.005

[b] App server : WAS 6.0.2.15[b/]

We have implemented our own id generator. The doWorkInIsolation() method throws up the above error when it tries to suspend the JTA transaction and open a JDBC connection.

tulips

Joined: Mon Mar 29, 2010 10:45 pm
Posts: 6

We too have the very same issue while working with Websphere 6.1 and EJB3 Feature pack along with Hibernate as persistence provider. I could see several queries raised on the same subject but with no valid response on the issue.

With websphere in specific, an attempt to suspend() the transaction throws unsupported exception. But the work around of using WebsphereTransactionManager instead of WebsphereExtendedTransactionManagerLookup works.

Can anyone please confirm if there is a neat solution to this problem ?
We’ve tried with almost all versions of hibernate starting with 3.0.

Источник

Русские Блоги

О jpa org.springframework.dao.springdataaccessresourceusageexception: Solutions Excession: решение

Сообщение об ошибке:

org.springframework.dao.InvalidDataAccessResourceUsageException: error performing isolated work; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: error performing isolated work

Проект Scraphboot был добавлен в проект Springboot. Я не нашел никаких проблем в течение длительного времени. Я не нашел никаких проблем, измените данные и запросы данных, то есть при вставке времени данных, это действительно головная боль.

Решением является объявление о стратегии = GeneratyType.identity в использовании стратегии генерации первичного ключа самостоятельного роста, и анализ окончательной проблемы может заключаться в том, что база данных не поддерживает, ни версия проблемы, у меня нет подробного исследование, но проблема решена

Интеллектуальная рекомендация

IView CDN Загрузка значка шрифта нормальная, а значок шрифта не может быть загружен при локальной загрузке JS и CSS

Используйте iview, чтобы сделать небольшой инструмент. Чтобы не затронуть другие платформы, загрузите JS и CSS CDN на локальные ссылки. В результате значок шрифта не может быть загружен. Просмо.

Критическое: ошибка настройки прослушивателя приложения класса org.springframework.web.context.ContextLoaderLis

1 Обзор Серверная программа, которая обычно запускалась раньше, открылась сегодня, и неожиданно появилась эта ошибка. Интуитивно понятно, что не хватает связанных с Spring пакетов, но после удаления п.

1086 Не скажу (15 баллов)

При выполнении домашнего задания друг, сидящий рядом с ним, спросил вас: «Сколько будет пять умножить на семь?» Вы должны вежливо улыбнуться и сказать ему: «Пятьдесят три». Это.

Pandas применяют параллельный процесс приложения, многоядерная скорость очистки данных

В конкурсе Algorith Algorith Algorith Algorith Algorith 2019 года используется многофункциональная уборка номера ускорения. Будет использовать панды. Но сама панда, кажется, не имеет механизма для мно.

PureMVC Learning (Tucao) Примечания

Справочная статья:Введение подробного PrueMVC Использованная литература:Дело UnityPureMvc Основная цель этой статьи состоит в том, чтобы организовать соответствующие ресурсы о PureMVC. Что касается Pu.

Источник

Русские Блоги

Различные аномальные ямы, возникающие при использовании Hibernate

Предисловие

Сегодня, когда я использовал SpringBoot для интеграции Hibernate, я столкнулся с некоторыми ненормальными проблемами при тестировании.Я готов подвести итоги. Запишите проблему, надеясь помочь вам ее решить.

Интегрированная среда

  • SpringBoot 2.1.1
  • JDK1.8
  • Hibernate5.3.7

Исключение первое

Информация об исключении выглядит следующим образом
Код следующий (Дао)

Следующий код в основном пишет запрос, чтобы узнать, существуют ли заголовок статьи и категория одновременно, используя метод параметра установки точки. После того, как другие блоггеры увидели, что Hibernate4.1, символ точки запроса в HQL был улучшен. , Поскольку я использую здесь старомодный заполнитель, я сообщил о вышеуказанном исключении.

Решение

Как видно из предупреждающего сообщения, рекомендуется использовать именованные параметры или заполнители JPA для замены старого метода запроса заполнителя.

  • Метод первый, перейти на именованные параметры
  • Метод 2: изменить способ расположения точки JPA
  • Примечание: где «?» Назад «0» Представляет позицию индекса, которая может повторяться в известном предложении HQL и не обязательно начинаться с 0, но может быть любым числом, но параметр должен соответствовать точке.
  • После использования последних двух методов запроса для модификации исключений не будет, лично рекомендую использовать метод первый , Это выглядит немного более интуитивно понятным, а производительность относительно лучше.
  • Журнал печати успешного оператора SQL

Аномалия вторая

Информация об исключении выглядит следующим образом
Код следующий (Сервис)

Следующий код сначала определяет, существует ли статья article, и выполняет метод добавления, если она не существует.

Решение

Из-за использования EntityManager В ходе выполнения Добавления и удаления Необходимо добавить транзакцию Transactional , Поскольку я не добавлял его сюда, произошло вышеуказанное исключение.

  • Добавить в @Transactional Жестяная банка
  • Обратите внимание, что добавление транзакции может быть добавлено непосредственно в метод или непосредственно в класс.Добавление в класс означает, что каждый метод имеет транзакцию от своего имени.
  • Печать журнала добавить успешный оператор SQL

Исключение третье

Информация об исключении выглядит следующим образом
код показать, как показано ниже

Вот та же ошибка при выполнении метода добавления. Я видел, как другие блоггеры говорили, что идентификатор увеличивается самостоятельно. Я установил здесь GenerationType.AUTO , Таким образом, произойдет вышеуказанное исключение.

Решение

Изменить класс сущности @GeneratedValue Стратегия может быть AUTO Приписывать IDENTITY Атрибуты.

Выше приведены некоторые из ям, с которыми я столкнулся, и они будут обновляться в будущем. Если у вас есть какие-либо вопросы, оставьте сообщение и посмотрите первый ответ.

Наконец, прикрепите:SpringBoot объединяет семейную корзину добро пожаловать star Спасибо за поддержку.

Источник

Adblock
detector

JBossDeveloper

We are in process of upgrading to 7.1 from 4.2.3a. During this excersize I did few changes to my hibernate.cfg.xml. Attached hibernate.cfg.xml

As well as here is standalone.xml entries:

And I am getting following error:

12:00:26,470 WARN [org.hibernate.util.JDBCExceptionReporter] (http—127.0.0.1-8080-2) SQL Error: 0, SQLState: null

12:00:26,471 ERROR [org.hibernate.util.JDBCExceptionReporter] (http—127.0.0.1-8080-2) You cannot commit during a managed transaction!

12:00:26,472 ERROR [yyy_common.yyyUserActivityException] (http—127.0.0.1-8080-2) [yyyUserActivity][yyyUserActivityException][myBean][createConnection] Failed to create connection: org.hibernate.exception.GenericJDBCException: error performing isolated work

at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103) [hibernate3.jar:3.2.6.ga]

at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91) [hibernate3.jar:3.2.6.ga]

at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) [hibernate3.jar:3.2.6.ga]

at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29) [hibernate3.jar:3.2.6.ga]

at org.hibernate.engine.transaction.Isolater$JdbcDelegate.delegateWork(Isolater.java:207) [hibernate3.jar:3.2.6.ga]

at org.hibernate.engine.transaction.Isolater.doIsolatedWork(Isolater.java:43) [hibernate3.jar:3.2.6.ga]

at org.hibernate.engine.TransactionHelper.doWorkInNewTransaction(TransactionHelper.java:51) [hibernate3.jar:3.2.6.ga]

at org.hibernate.id.TableGenerator.generate(TableGenerator.java:94) [hibernate3.jar:3.2.6.ga]

Attached full log. Any pointer would be really appreciated.

Источник

org.hibernate.exception.SQLGrammarException when saving object with Many-to-Many and many-to-one relationships #2137

Comments

pacu commented Oct 12, 2015

I have this simple model.

Course 1—> * Level * ——- * Excercise

I tried to use both jhipster-uml and yeoman generators getting the same results
I can create a Course without problems.
I can create an Exercise as well
But I can’t create a Level for some reason.
This is the error shown in the browser

this is part of the log and trace that I got

This is how I created the entities using yeoman (I swear I read the docs and googled a lot before posting this)
yo jhipster:entity course

yo jhipster:entity exercise

yo jhipster:entity level

The text was updated successfully, but these errors were encountered:

ErickSanVal commented Oct 12, 2015

Well, somebody correct me if I’m wrong but it seems that the REST request is missing the ‘course_id’ parameter. Does it have to do with that?

pacu commented Oct 12, 2015

could it be because «order» is a reserved keyword on postgres?

ErickSanVal commented Oct 12, 2015

Oh, yeah, have you tried changing the name of the field?

pacu commented Oct 13, 2015

I’m having other kind of problems. I’ve created a new project with the same
models but the NavBar is not working and localhost:8080/#/courses is
redirecting me to the home page.

On Mon, Oct 12, 2015 at 8:18 PM, Erick notifications@github.com wrote:

Oh, yeah, have you tried changing the name of the field?


Reply to this email directly or view it on GitHub
#2137 (comment)
.

IEEE Member# 91130670
Home:+5411 5032 3615
Mobile: +5411 6096 2879

jdubois commented Oct 13, 2015

@pacu if you have another problem, please open another ticket.

Yes I’m 99% sure this issue is because your field is called «order»:

  • Your ticket is really good (which is unusual!), but you missed the most important thing, the SQL request! As you have an SQL grammar exception, that was the most important part.
  • We have lists of reserved keywords for many things, but not for Postgresql, as I couldn’t find a good list (the official list has lots and lots of reserved keywords, which you can in fact use without any issue, and that’s annoying because a lot of «good» names are reserved)

-> Maybe we should do our own reserved keywords list? Wouldn’t be perfect, but better than nothing

I’m closing this as you seem to moved on to another issue, and as I’m pretty sure this is this reserved keyword issue: if you still have the issue, please add a comment and I’ll reopen it.

Источник

Common Hibernate Exceptions Every Developer Must Know

Get access to all my video courses, 2 monthly Q&A calls, monthly coding challenges, a community of like-minded developers, and regular expert sessions.

Every framework has a set of exceptions that indicate common error scenarios. Understanding them will help you turn a task that could drag along for days into a quickly-implemented feature. When working with Hibernate, they tell you about issues with your database queries, mapping mistakes, and problems during write operations.

In this article, I want to show you the most common exceptions and explain how you can avoid or fix them.

Query-Related Exceptions

These are the most common Hibernate exceptions. Sometimes, they are caused by a simple typo in your statement or because you called the wrong Query interface method. However, they can also indicate potential performance issues or data inconsistencies.

NonUniqueResultException

All JPA implementations throw the NonUniqueResultException if you call the getSingleResult method on a Query interface and the executed query returns more than one record.

The NonUniqueResultException most often occurs because:

  • You intentionally wrote a query that returns multiple records and tried executing it by calling the getSingleResult() instead of the getResultList() method. To be honest, that happens to me quite regularly. Luckily, it’s very quick and easy to fix by calling the getResultList() method.
  • You wanted to create a query that returns only one record, but the WHERE clause isn’t as restrictive as you thought. In that case, please check my Guide to JPQL. It tells you everything you need to know to improve your query.
  • You wrote a query that was supposed to return only one record and you stumbled upon inconsistent data. If that happens, then it’s hopefully just some artificially created test data. But, in any case, you should double-check your business logic and add a unique constraint to your table model.

QuerySyntaxException

If Hibernate throws a QuerySyntaxException, you have made a mistake in your JPQL query. In most cases, the mistake will be a simple typo in one of JPQL’s reserved keywords.

As you can see in the following log message, Hibernate tells you which part of the query it didn’t understand. In this example, I misspelled the word LEFT in my LEFT JOIN clause.

SQLGrammarException

An SqlGrammarException is very similar to a QuerySyntaxException. It indicates a mistake in a native SQL statement.

Unfortunately, Hibernate’s exception doesn’t provide a lot of information about the actual error. It only tells you that it was unable to extract the ResultSet. But, if you take a look at the end of the stack trace, you should find the exception thrown by your JDBC driver. It usually tells you why the query failed.

LazyInitializationException

The LazyInitializationException might not look like a query-related exception because it happens much later. Hibernate throws it if you try to initialize a lazily fetched association without an active Hibernate Session. This usually happens in your UI layer after your backend committed the transaction and closed the Session. Even though it might not look like it, it’s caused by a query that didn’t fetch the required association.

As you can see in the message below, Hibernate tells you which association it wasn’t able to initialize.

You can fix this exception in multiple ways. The easiest and most commonly used solution is a JOIN FETCH clause. You can use it in your JPQL query to tell Hibernate to initialize the referenced association.

MultipleBagFetchException

If you model your to-many associations as java.util.Lists and try to initialize a number of them using a JOIN FETCH clause, Hibernate will throw a MultipleBagFetchException.

As I explained in more detail in a previous article, you can fix this exception in two ways:

1. You can change the attribute type to a java.util.Set.

2. You can use multiple queries that use only one JOIN FETCH clause each. This approach works because Hibernate ensures that a Session contains only one entity object for each database record. If you select the same one with different fetching behavior, Hibernate will merge them in memory.

Mapping-Related Exceptions

I will keep this section short because mapping-related exceptions are rare. That’s mostly because mapping is defined once and used during the entire project.

MappingException: The Increment Size of the [author_seqence] Sequence Is Set to [50] in the Entity Mapping While the Associated Database Sequence Increment Size Is [1]

If you use a database sequence to generate your primary key values and define a @SequenceGenerator, you might get the following exception:

Hibernate throws this exception because it provides an optimization based on the default allocationSize of the @SequenceGenerator. Based on that default setting, the database sequence should get incremented by 50 every time you request a new value. Hibernate then uses the value from the sequence and increments it 49 times internally before requesting another value. This drastically reduces the number of executed JDBC statements.

During the deployment of your persistence layer, Hibernate checks if the referenced database sequence gets incremented by the defined allocationSize. If that’s not the case, it throws a MappingException.

I recommend fixing this exception by increasing the step size on your database sequence. It enables you to use Hibernate’s optimization to improve the performance of your insert operations. If you cannot change the database sequence, you need to set the allocationSize of the @SequenceGenerator to one.

Update-Related Exceptions

Hibernate throws this kind of exception to inform you about problems during write operations. The two most common ones are the OptimisticLockException and the PersistentObjectException. While the first one is expected to occur at runtime, the second one is always an implementation error.

OptimisticLockException

JPA and Hibernate provide two build-in mechanisms to manage concurrent updates. One of them is called optimistic locking. It causes an OptimisticLockException whenever two or more transactions try to update the same database record at the same time. That lets all except the first transaction fail and prevents the concurrent modification of the record.

Optimistic and pessimistic locking are easy and complex at the same time, but that’s a whole other topic. If you want to learn more about it, please join my Hibernate Performance Tuning Online Training.

Technically, there are a few options for fixing an OptimisticLockException. But realistically, all of them require you to merge the operations performed in the parallel transactions. The best and most reliable way to do that is to show an error message to the user when the exception occurs. The user can then find the differences between both changes, resolve errors or inconsistencies, and perform another update.

PersistentObjectException: Detached Entity Passed to Persist

There are two main scenarios in which Hibernate throws this exception.

The first happens when you configure a primary key generation strategy for an entity and set the primary key value programmatically before persisting a new entity. You can easily fix that by removing the code that sets the primary key value. If you’re using field-based access, you should also remove the setter method for the primary key attribute. This prevents you from accidentally setting that attribute in the future.

The second scenario happens when you call the persist method of the EntityManager with a detached entity.

This is usually the case because you got an entity object from a client application and tried to persist it. In this case, you can fix the exception by calling the merge method on the EntityManager.

Conclusion

If you’re using a framework to implement your application, you should be familiar with its most common exceptions. Hibernate is a complex and powerful framework. So, it’s no surprise that you need to be familiar with a bunch of exceptions.

Most of them are query-related because querying data is highly flexible and the most used part of the framework. The good news is that all of these exceptions include a good description of the error so that you can easily fix it.

Источник

Caused by org hibernate exception sqlgrammarexception error performing isolated work

Опытный

Профиль
Группа: Участник
Сообщений: 253
Регистрация: 27.3.2006

Репутация: нет
Всего: нет

ochnev
Дата 16.6.2008, 16:34 (ссылка) | (нет голосов) Загрузка .
Код
Query getPayments = session.createQuery(«from InstructorPayment payment order by payment.id asc»);
List payments = getPayments.list();

На 2-й строке получаю SQLGrammarException:

Цитата
org.hibernate.exception.SQLGrammarException: could not execute query
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
org.hibernate.loader.Loader.doList(Loader.java:2223)
org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
org.hibernate.loader.Loader.list(Loader.java:2099)
org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:378)
org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:338)
org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:172)
org.hibernate.impl.SessionImpl.list(SessionImpl.java:1121)
org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
ru.sixthsense.servlet.InstructorWorkHistoryServlet.doGet(InstructorWorkHistoryServlet.java:206)
javax.servlet.http.HttpServlet.service(HttpServlet.java:690)

Таблица пустая, но не из-за этого же оно падает. Мэппинг проверил — вроде всё нормально.

Код
CREATE TABLE instructor_payment (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
amount DECIMAL(10,2) NOT NULL,
bonusOrFine DECIMAL(10,2) NOT NULL,
pay_date DATETIME NOT NULL,
verified DATETIME,
comment VARCHAR(100),
instructor_id INTEGER NOT NULL REFERENCES users,
manager_id INTEGER NOT NULL REFERENCES users
) CHARACTER SET utf8;

Всё раньше работало, вдруг сломалось на ровном месте. Я базу переделывал, но нужная таблица на месте.
Что происходит? Как найти реальную причину SQLGrammarException при таком stack trace, в котором нет ни малейших подробностей о проблеме?

AntonSaburov
Дата 16.6.2008, 17:22 (ссылка) | (нет голосов) Загрузка .

Штурман

Профиль
Группа: Модератор
Сообщений: 5658
Регистрация: 2.7.2002
Где: Санкт-Петербург

Репутация: 8
Всего: 118

Добавь в hibernate.cfg.xml

Тогда можно будет посмотреть реальный SQL — ну и увидишь. Возможно

necromancer
Дата 16.6.2008, 17:25 (ссылка) | (нет голосов) Загрузка .

Опытный

Профиль
Группа: Участник
Сообщений: 317
Регистрация: 26.7.2006
Где: Москва

Репутация: 6
Всего: 7

Zlatogorov
Дата 16.6.2008, 17:40 (ссылка) | (нет голосов) Загрузка .

Шустрый

Профиль
Группа: Участник
Сообщений: 117
Регистрация: 18.12.2007
Где: BW,Stuttgart

Репутация: нет
Всего: 1

, тип должен стоять java.lang.Double , ну и т.д.
А просто double не существует.
Ну и timestamp должен быть java.util.Date.

Это сообщение отредактировал(а) Zlatogorov — 16.6.2008, 17:44

tux
Дата 16.6.2008, 20:29 (ссылка) | (нет голосов) Загрузка .

Летатель

Профиль
Группа: Участник Клуба
Сообщений: 1853
Регистрация: 10.2.2005
Где: msk.ru

Репутация: 74
Всего: 132

Цитата(ochnev @ 16.6.2008, 16:34 )
Всё раньше работало, вдруг сломалось на ровном месте.

Точно работало? Вот, например, в маппинге колонка называется bonus_or_fine, а в таблице bonusOrFine.

Цитата(Zlatogorov @ 16.6.2008, 17:40 )
К примеру здесь

, тип должен стоять java.lang.Double , ну и т.д.
А просто double не существует.

Опытный

Профиль
Группа: Участник
Сообщений: 253
Регистрация: 27.3.2006

Репутация: нет
Всего: нет

Точно.
Каюсь.
Что-то переделывал и в попыхах copy/paste не там сделал.

ochnev
Дата 16.6.2008, 22:01 (ссылка) | (нет голосов) Загрузка .
Правила форума «Java»
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс «транслит«, если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка «Пометить как решённый» находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux.

0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java EE (J2EE) и Spring | Следующая тема »

[ Время генерации скрипта: 0.2326 ] [ Использовано запросов: 21 ] [ GZIP включён ]

Источник

Adblock
detector

Проект Spring Boot выполняет ошибку: org.hibernate.exception.sqlgrammarexception: ошибка выполняет изолированную;

    • вопрос:
    • Причины и решения

вопрос:

Сегодня, когда проводится тест проекта Spring Boot, операция сообщается, как показано ниже:


org.springframework.dao.InvalidDataAccessResourceUsageException: error performing isolated work; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: error performing isolated work
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:281)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor C r u d M e t h o d M e t a d a t a P o p u l a t i n g M e t h o d I n t e r c e p t o r . i n v o k e ( C r u d M e t h o d M e t a d a t a P o s t P r o c e s s o r . j a v a : 178 ) a t o r g . s p r i n g f r a m e w o r k . a o p . f r a m e w o r k . R e f l e c t i v e M e t h o d I n v o c a t i o n . p r o c e e d ( R e f l e c t i v e M e t h o d I n v o c a t i o n . j a v a : 186 ) a t o r g . s p r i n g f r a m e w o r k . a o p . i n t e r c e p t o r . E x p o s e I n v o c a t i o n I n t e r c e p t o r . i n v o k e ( E x p o s e I n v o c a t i o n I n t e r c e p t o r . j a v a : 93 ) a t o r g . s p r i n g f r a m e w o r k . a o p . f r a m e w o r k . R e f l e c t i v e M e t h o d I n v o c a t i o n . p r o c e e d ( R e f l e c t i v e M e t h o d I n v o c a t i o n . j a v a : 186 ) a t o r g . s p r i n g f r a m e w o r k . a o p . f r a m e w o r k . J d k D y n a m i c A o p P r o x y . i n v o k e ( J d k D y n a m i c A o p P r o x y . j a v a : 212 ) a t c o m . s u n . p r o x y . CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) at com.sun.proxy. CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178)atorg.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)atorg.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)atorg.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)atorg.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)atcom.sun.proxy.Proxy105.save(Unknown Source)

Причины и решения

После проверки соответствующих вопросов в Интернете я узнал, что это было причиной идентификатора идентификатора идентификатора.
Правильный подход должен быть добавлен в идентификатор:

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)

Как показано ниже:

Author Message

Post subject: Table ‘hibernate_sequence’ doesn’t exist on MySQL

PostPosted: Tue Aug 22, 2017 1:12 am 

Beginner
Beginner



Joined: Tue Aug 08, 2017 12:14 am
Posts: 44

Hi experts,

I got error that Hibernate-sequence doesn’t exist.

And then I tried to follow the advice from

https://stackoverflow.com/questions/329 … esnt-exist

However, when I put it in my hibernate.cfg.xml file, eclipse gives an x beside the line

Code:

<?xml version=»1.0″ encoding=»UTF-8″?>
<!DOCTYPE hibernate-configuration PUBLIC «-//Hibernate/Hibernate Configuration DTD//EN» «http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd»>

   <hibernate-configuration>

         <session-factory>
            <!— Database connection settings —>
    <property name=»connection.driver_class»>com.mysql.jdbc.Driver</property>
    <property name=»connection.url»>jdbc:mysql://localhost:3306/hi5</property>
    <property name=»connection.username»>root</property>
    <property name=»connection.password»>root</property>
   <!— JDBC connection pool (use the built-in) —>
    <property name=»connection_pool_size»>true</property>

<!— Use the C3P0 connection pool. —> 
        <property name=»c3p0.min_size»>3</property> 
        <property name=»c3p0.max_size»>5</property> 
        <property name=»c3p0.timeout»>1800</property>

      <!— SQL dialect —>
    <property name=»hibernate.dialect»>org.hibernate.dialect.MySQLDialect</property>

    <!— Disable the second-level cache —>
    <property name=»cache.provider_class»>org.hibernate.NoCacheProvider</property>

<property name=»hibernate.current_session_context_class»>org.hibernate.context.internal.ThreadLocalSessionContext</property>
    <!— Echo all executed SQL to stdout —>
    <property name=»show_sql»>1</property>
    <property key=»hibernate.id.new_generator_mappings»>false</property>
    <mapping class=»model.Tutor»/>
    <mapping class=»model.Subject»/>

</session-factory>
</hibernate-configuration>   

Where should I put this line and why am I getting an error ?

Top

Profile  

vlad

Post subject: Re: hibernate.id.new_generator_mappings property set to false

PostPosted: Wed Aug 23, 2017 4:00 am 

Hibernate Team
Hibernate Team



Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania

Code:

<property name=»show_sql»>1</property>
<property key=»hibernate.id.new_generator_mappings»>false</property>

If you look closer to these two lines, you’ll see that one uses the name attribute while the other uses key instead.

The fix is as simple as this:

Code:

s/key/name

Top

Profile  

karengsh

Post subject: Re: hibernate.id.new_generator_mappings property set to false

PostPosted: Wed Aug 23, 2017 6:14 am 

Beginner
Beginner



Joined: Tue Aug 08, 2017 12:14 am
Posts: 44

vlad wrote:

Code:

<property name=»show_sql»>1</property>
<property key=»hibernate.id.new_generator_mappings»>false</property>

If you look closer to these two lines, you’ll see that one uses the name attribute while the other uses key instead.

The fix is as simple as this:

Code:

s/key/name

Hi,

I have changed it to <property name=»hibernate.id.new_generator_mappings»>false</property> and there is no more error. Tks.

However, I am still getting the following error…
I tried with @GeneratedValue(strategy = GenerationType.AUTO) or changed it to GenerationType.Sequence…all not working.

What could be cause of this error below ?

Code:

Aug 23, 2017 6:09:13 PM org.hibernate.id.enhanced.TableStructure$1$1 execute
ERROR: could not read a hi value
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘hi5.hibernate_sequence’ doesn’t exist
   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
   at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
   at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
   at com.mysql.jdbc.Util.getInstance(Util.java:387)
   at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:941)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3870)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3806)
   at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2470)
   at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2617)
   at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2550)
   at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
   at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1962)
   at org.hibernate.id.enhanced.TableStructure.executeQuery(TableStructure.java:216)
   at org.hibernate.id.enhanced.TableStructure.access$300(TableStructure.java:46)
   at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:138)
   at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:126)
   at org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:55)
   at org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:34)
   at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:57)
   at org.hibernate.id.enhanced.TableStructure$1.getNextValue(TableStructure.java:125)
   at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
   at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:432)
   at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
   at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
   at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
   at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
   at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
   at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
   at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:689)
   at org.hibernate.internal.SessionImpl.save(SessionImpl.java:681)
   at org.hibernate.internal.SessionImpl.save(SessionImpl.java:676)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
   at java.lang.reflect.Method.invoke(Method.java:497)
   at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:355)
   at com.sun.proxy.$Proxy33.save(Unknown Source)
   at DAOSql.tutorDAOImpl.insertTutor(tutorDAOImpl.java:63)
   at Business.Manager.insertTutor(Manager.java:24)
   at controller.tutorController.doPost(tutorController.java:128)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
   at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
   at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
   at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
   at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
   at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
   at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
   at java.lang.Thread.run(Thread.java:745)

Aug 23, 2017 6:09:13 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Aug 23, 2017 6:09:13 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Table ‘hi5.hibernate_sequence’ doesn’t exist
org.hibernate.exception.SQLGrammarException: error performing isolated work
   at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
   at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
   at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
   at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
   at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:79)
   at org.hibernate.id.enhanced.TableStructure$1.getNextValue(TableStructure.java:125)
   at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
   at org.hibernate.id.enhanced.SequenceStyleGenerator.generate(SequenceStyleGenerator.java:432)
   at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:105)
   at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
   at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
   at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
   at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
   at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
   at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:689)
   at org.hibernate.internal.SessionImpl.save(SessionImpl.java:681)
   at org.hibernate.internal.SessionImpl.save(SessionImpl.java:676)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
   at java.lang.reflect.Method.invoke(Method.java:497)
   at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:355)
   at com.sun.proxy.$Proxy33.save(Unknown Source)
   at DAOSql.tutorDAOImpl.insertTutor(tutorDAOImpl.java:63)
   at Business.Manager.insertTutor(Manager.java:24)
   at controller.tutorController.doPost(tutorController.java:128)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
   at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
   at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
   at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
   at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
   at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
   at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
   at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘hi5.hibernate_sequence’ doesn’t exist
   at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
   at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
   at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
   at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
   at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
   at com.mysql.jdbc.Util.getInstance(Util.java:387)
   at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:941)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3870)
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3806)
   at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2470)
   at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2617)
   at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2550)
   at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
   at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1962)
   at org.hibernate.id.enhanced.TableStructure.executeQuery(TableStructure.java:216)
   at org.hibernate.id.enhanced.TableStructure.access$300(TableStructure.java:46)
   at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:138)
   at org.hibernate.id.enhanced.TableStructure$1$1.execute(TableStructure.java:126)
   at org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:55)
   at org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:34)
   at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:57)
   … 43 more
Aug 23, 2017 6:09:13 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/hi5]
Aug 23, 2017 6:09:13 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections close
ERROR: Collection leak detected: there are 1 unclosed connections upon shutting down pool jdbc:mysql://localhost:3306/hi5

Top

Profile  

vlad

Post subject: Re: hibernate.id.new_generator_mappings property set to false

PostPosted: Wed Aug 23, 2017 6:26 am 

Hibernate Team
Hibernate Team



Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania

On a production setup or a real application, you’d need to use an automatic schema migration tool, like Flyway.

Because this is just a test project, you can auto generate your schema:

Code:

<property name=»hibernate.hbm2ddl.auto»>update</property>

If you don’t generate the DB schema automatically, then you’ll need to do it manually according to what Hibernate expects to find in the DB according to your mappings.

Anyway, since you are using MySQL, using AUTO is quite a bad idea. Check out this article for more details.

But, there’s even more.

You decide to set the hibernate.id.new_generator_mappings property to false for no good reason. This property should be set to false only when migrating from Hibernate 4 to 5 while relying on hi/lo optimization for the sequence-based optimizers. I doubt that’s you use case here.

What you need to do at this point is to:

1) Read the Hibernate User Guide.
1) Read these Hibernate tutorials on vladmihalcea.com.

Top

Profile  

karengsh

Post subject: Re: hibernate.id.new_generator_mappings property set to false

PostPosted: Thu Aug 24, 2017 2:21 am 

Beginner
Beginner



Joined: Tue Aug 08, 2017 12:14 am
Posts: 44

vlad wrote:

On a production setup or a real application, you’d need to use an automatic schema migration tool, like Flyway.

Because this is just a test project, you can auto generate your schema:

Code:

<property name=»hibernate.hbm2ddl.auto»>update</property>

If you don’t generate the DB schema automatically, then you’ll need to do it manually according to what Hibernate expects to find in the DB according to your mappings.

Anyway, since you are using MySQL, using AUTO is quite a bad idea. Check out this article for more details.

But, there’s even more.

You decide to set the hibernate.id.new_generator_mappings property to false for no good reason. This property should be set to false only when migrating from Hibernate 4 to 5 while relying on hi/lo optimization for the sequence-based optimizers. I doubt that’s you use case here.

What you need to do at this point is to:

1) Read the Hibernate User Guide.
1) Read these Hibernate tutorials on vladmihalcea.com.

Tks for the pointer.
Both strategies I attempted did not work out.
I attempted the first one which is ‘native’… it gives me error :
No generator named ‘native’ is defined in the persistence unit.

Then, I followed the sequence strategy as per your tutorial.

However, I am still getting another error :

Code:

Initial SessionFactory creation failed.org.hibernate.MappingException: org.hibernate.dialect.MySQLDialect does not support pooled sequences
Aug 24, 2017 2:18:16 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [tutorController] in context with path [/Hi5S] threw exception [Servlet execution threw an exception] with root cause
org.hibernate.MappingException: org.hibernate.dialect.MySQLDialect does not support pooled sequences
   at org.hibernate.dialect.Dialect.getCreateSequenceString(Dialect.java:905)
   at org.hibernate.dialect.Dialect.getCreateSequenceStrings(Dialect.java:863)
   at org.hibernate.tool.schema.internal.StandardSequenceExporter.getSqlCreateStrings(StandardSequenceExporter.java:28)
   at org.hibernate.tool.schema.internal.StandardSequenceExporter.getSqlCreateStrings(StandardSequenceExporter.java:18)
   at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:224)
   at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:110)
   at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183)
   at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
   at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:309)
   at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)
   at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
   at util.HibernateUtil.<clinit>(HibernateUtil.java:18)
   at DAOSql.tutorDAOImpl.insertTutor(tutorDAOImpl.java:42)
   at Business.Manager.insertTutor(Manager.java:24)
   at controller.tutorController.doPost(tutorController.java:128)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
   at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
   at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
   at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
   at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
   at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
   at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
   at java.lang.Thread.run(Thread.java:745)

Top

Profile  

vlad

Post subject: Re: Table ‘hibernate_sequence’ doesn’t exist on MySQL

PostPosted: Thu Aug 24, 2017 2:43 am 

Hibernate Team
Hibernate Team



Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania

Most likely, you forced MySQL to use a SEQUENCE which is not supported in the latest MySQL versions 5.7 or 8.0.

Top

Profile  

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Sqldumper error log
  • Sqlcmd error microsoft odbc driver 17 for sql server tcp provider error code 0x2746
  • Sqlceexception occurred native error 25035
  • Sqlalchemy timeout error
  • Sqlalchemy database error

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии