Содержание
- Hibernate — @ElementCollection — Strange delete/insert behavior
- 4 Answers 4
- Primary keys in CollectionTable
- error while updating person: HHH000346: Error during managed flush #281
- Comments
- Fix for “object references an unsaved transient instance – save the transient instance beforeQuery flushing” in Hibernate
- 1. Reproducing Issue
- 2. Understanding Root Cause
- 3. Solution
- 4. Conclusion
- Русские Блоги
- ERROR ExceptionMapperStandardImpl HHH000346: Error during managed flush [org.hibernate.TransientObje
- Эта ошибка обычно происходит во многих, многие в
- Интеллектуальная рекомендация
- Реализация оценки приложения iOS
- JS функциональное программирование (е)
- PWN_JarvisOJ_Level1
- Установка и развертывание Kubernetes
- На стороне многопроцессорного сервера — (2) *
- Русские Блоги
- ERROR: HHH000346: Error during managed flush [org.hibernate.TransientPropertyValueException: object
- Интеллектуальная рекомендация
- Реализация оценки приложения iOS
- JS функциональное программирование (е)
- PWN_JarvisOJ_Level1
- Установка и развертывание Kubernetes
- На стороне многопроцессорного сервера — (2) *
Hibernate — @ElementCollection — Strange delete/insert behavior
Given the following class structure, when I try to add a new location to the list of Person’s Locations, it always results in the following SQL queries:
Hibernate (3.5.x / JPA 2) deletes all associated records for the given Person and re-inserts all previous records, plus the new one.
I had the idea that the equals/hashcode method on Location would solve the problem, but it didn’t change anything.
Any hints are appreciated!
4 Answers 4
The problem is somehow explained in the page about ElementCollection of the JPA wikibook:
Primary keys in CollectionTable
The JPA 2.0 specification does not provide a way to define the Id in the Embeddable . However, to delete or update a element of the ElementCollection mapping, some unique key is normally required. Otherwise, on every update the JPA provider would need to delete everything from the CollectionTable for the Entity , and then insert the values back. So, the JPA provider will most likely assume that the combination of all of the fields in the Embeddable are unique, in combination with the foreign key ( JoinColunm (s)). This however could be inefficient, or just not feasible if the Embeddable is big, or complex.
And this is exactly (the part in bold) what happens here (Hibernate doesn’t generate a primary key for the collection table and has no way to detect what element of the collection changed and will delete the old content from the table to insert the new content).
However, if you define an @OrderColumn (to specify a column used to maintain the persistent order of a list — which would make sense since you’re using a List ), Hibernate will create a primary key (made of the order column and the join column) and will be able to update the collection table without deleting the whole content.
Something like this (if you want to use the default column name):
Источник
error while updating person: HHH000346: Error during managed flush #281
while updating people i got a lot of error with the same error (and with various person , not the same)
[28.03.2016 23:24:58] ERROR org.hibernate.internal.SessionImpl — HHH000346: Error during managed flush [Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1]
[28.03.2016 23:24:58] ERROR org.yamj.core.service.metadata.MetadataScannerService — Failed storing person filmography 12031-‘Paul Anderson’
[28.03.2016 23:24:58] ERROR org.yamj.core.service.metadata.MetadataScannerService — Storage error
org.springframework.orm.hibernate5.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.springframework.orm.hibernate5.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:206)
at org.springframework.orm.hibernate5.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:741)
at org.springframework.orm.hibernate5.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:589)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:485)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at org.yamj.core.database.service.MetadataStorageService$$EnhancerBySpringCGLIB$$825acabf.updateScannedPersonFilmography()
at org.yamj.core.service.metadata.MetadataScannerService.scanFilmography(MetadataScannerService.java:209)
at org.yamj.core.service.metadata.MetadataScannerService.processQueueElement(MetadataScannerService.java:68)
at org.yamj.core.scheduling.QueueProcessRunner.run(QueueProcessRunner.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:67)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:54)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:46)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3106)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2985)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3365)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:145)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:560)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1295)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:468)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3135)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2352)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:147)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
at org.springframework.orm.hibernate5.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:581)
. 14 more
The text was updated successfully, but these errors were encountered:
Источник
Fix for “object references an unsaved transient instance – save the transient instance beforeQuery flushing” in Hibernate
When I am working with association in JPA with Hibernate, Error during managed flush [org.hibernate.TransientObjectException: object references an unsaved transient instance – save the transient instance beforeQuery flushing …] is one of the common error often I have seen.
Lets’s see when this Error occur and how to fix this issue. First let’s reproduce the issue.
1. Reproducing Issue
Entity Mappings:
Let’s save Branch entity.
Output:
We will get ERROR: HHH000346: Error during managed flush [org.hibernate.TransientObjectException: object references an unsaved transient instance – save the transient instance beforeQuery flushing: com.javabydeveloper.domain.Student]
2. Understanding Root Cause
Hibernate first inserted Branch record in database and trying to update foreign key BRANCH_ID in Student table. But Student record not yet inserted in DB. Which means, the Student entity state is transient in Persistence Context.
So, Branch object has reference (Student), which is an unsaved transient instance. We need to save Student (transient instance) before Hibernate flushing Branch.
3. Solution
In Hibernate, In Parent and Child table association mappings, this is a common issue. To fix the issue, we need to apply proper Cascading operation to the reference in Branch entity using CascadeType.
CascadeType propagates entity transitions from Parent to Child. For example, if you persist parent entity the referenced entities also get persisted before flushing. Let’s update the Branch entity using CascadeType.ALL.
Let’s run the program again and verify results.
Now, we can notice Student records get updated before updating BRANCH_ID foreign key in Student table.
4. Conclusion
We have seen the root cause of issue “object references an unsaved transient instance – save the transient instance beforeQuery flushing” in JPA with Hibernate and how to fix the issue.
Источник
Русские Блоги
ERROR ExceptionMapperStandardImpl HHH000346: Error during managed flush [org.hibernate.TransientObje
Эта ошибка обычно происходит во многих, многие в
Например: Я вот «пользовательские записи» UserID внешних ключевых постов, связанные с пользователем пользователя, когда пользователь входит в систему, пользователь, хранящийся на сеансе, получает пользователь, хранящийся на сеансе, когда пользовательские публикации, здесь я приобретающую пользователь Это нуль, поэтому пост внешнего ключа — это нуль, поэтому я здесь, чтобы установить UserID не может быть нулевой ошибкой
Справка Проверьте таблицу, связанную с другим столом, следует ли сохранять (настройку) в процессе таблицы
Интеллектуальная рекомендация
Реализация оценки приложения iOS
Есть два способа получить оценку приложения: перейти в App Store для оценки и оценка в приложении. 1. Перейдите в App Store, чтобы оценить ps: appid можно запросить в iTunes Connect 2. Встроенная оцен.
JS функциональное программирование (е)
Давайте рассмотрим простой пример, чтобы проиллюстрировать, как используется Reduce. Первый параметр Reduce — это то, что мы принимаем массив arrayOfNums, а второй параметр — функцию. Эта функция прин.
PWN_JarvisOJ_Level1
Nc первый Затем мы смотрим на декомпиляцию ida Перед «Hello, World! N» есть уязвимая_функция, проверьте эту функцию после ввода Видно, что только что появившийся странный адрес является пе.
Установка и развертывание Kubernetes
На самом деле, я опубликовал статью в этом разделе давным -давно, но она не достаточно подробно, и уровень не является ясным. Когда я развернулся сегодня, я увидел его достаточно (хотя это было успешн.
На стороне многопроцессорного сервера — (2) *
Обработка сигнала Родительский процесс часто очень занят, поэтому вы не можете просто вызвать функцию waitpid, чтобы дождаться завершения дочернего процесса. Затем обсудите решение. Обратитесь .
Источник
Русские Блоги
ERROR: HHH000346: Error during managed flush [org.hibernate.TransientPropertyValueException: object
Используйте JPA для реализации большего количества ошибок, когда возникает одно отношение. Ниже приводится сообщение об ошибке:
Причина в том, что для сохранения всех сущностей не существует операции по настойчивости. Код ошибки является примером:
При выполнении этого кода появится информация о ошибке выше. Когда два объекта пользователя и объект клиента выполняются в течение длительного времени, ошибка не работает нормально.
Ниже приводится результат нормальной работы:
Интеллектуальная рекомендация
Реализация оценки приложения iOS
Есть два способа получить оценку приложения: перейти в App Store для оценки и оценка в приложении. 1. Перейдите в App Store, чтобы оценить ps: appid можно запросить в iTunes Connect 2. Встроенная оцен.
JS функциональное программирование (е)
Давайте рассмотрим простой пример, чтобы проиллюстрировать, как используется Reduce. Первый параметр Reduce — это то, что мы принимаем массив arrayOfNums, а второй параметр — функцию. Эта функция прин.
PWN_JarvisOJ_Level1
Nc первый Затем мы смотрим на декомпиляцию ida Перед «Hello, World! N» есть уязвимая_функция, проверьте эту функцию после ввода Видно, что только что появившийся странный адрес является пе.
Установка и развертывание Kubernetes
На самом деле, я опубликовал статью в этом разделе давным -давно, но она не достаточно подробно, и уровень не является ясным. Когда я развернулся сегодня, я увидел его достаточно (хотя это было успешн.
На стороне многопроцессорного сервера — (2) *
Обработка сигнала Родительский процесс часто очень занят, поэтому вы не можете просто вызвать функцию waitpid, чтобы дождаться завершения дочернего процесса. Затем обсудите решение. Обратитесь .
Источник
This error occurs when you try to modify the primary key value of your Entity Class or Model class. Below are some solutions you can follow to solve this problem.
Solution 1
If you’re telling Hibernate to use a generator class (@GeneratedValue), maybe manually setting the value of the primary key is what’s causing the exception. So either remove @GeneratedValue from your Entity Class or don’t try to set the primary key property of Entity class manually.
Solution 2
If you want to modify the primary key value of your Entity class, you will have to first detach your Entity from session. To detach Entity from session you can use the detach() method of EntityManager interface. For more information on detach method, you can refer Oracle JavaEE API
Solution 3
If you are using xml file for bean configuration, then check what is the type of Primary key field that you have used in XML file and what is the type of Primary key field in Entity or Bean class. If both are different, then change anyone of them, so that both the types of primary key field are same.
For ex. in hbm.xml file if Primary key field (say id) has type of integer and in Entity or Bean class primary key field(say id) has type long.
If all the above solution doesn’t work, and you have yourself found some solution please write that below in comment sections please. It would surely help others.
When I am working with association in JPA with Hibernate, Error during managed flush [org.hibernate.TransientObjectException: object references an unsaved transient instance – save the transient instance beforeQuery flushing …] is one of the common error often I have seen.
Lets’s see when this Error occur and how to fix this issue. First let’s reproduce the issue.
1. Reproducing Issue
Entity Mappings:
@Entity public class Student implements Serializable { @Id private int id; @Column(name="CONTACT_NO") private String contactNo; private String fname; private String lname; // ... omitted setters and getters }
@Entity public class Branch implements Serializable { @Id @Column(name="BRANCH_ID") private int branchId; @Column(name="BRANCH_NAME") private String branchName; @Column(name="BRANCH_SHORT_NAME") private String branchShortName; private String description; //uni-directional one-to-many association to Student @OneToMany(orphanRemoval = true) @JoinColumn(name="BRANCH_ID") private List<Student> students; // .. omitted setters getters etc. }
Let’s save Branch entity.
Branch branch = new Branch(); branch.setBranchShortName("CSE"); branch.setBranchName("Computer Science and Engineering"); branch.setDescription("CSE department offers courses under ambitious curriculum in computer science .."); List<Student> students = new ArrayList<Student>(); students.add(getStudent1()); students.add(getStudent2()); branch.setStudents(students); entityManager.persist(branch); transaction.commit();
Output:
We will get ERROR: HHH000346: Error during managed flush [org.hibernate.TransientObjectException: object references an unsaved transient instance – save the transient instance beforeQuery flushing: com.javabydeveloper.domain.Student]
Hibernate: insert into Branch (BRANCH_NAME, BRANCH_SHORT_NAME, description) values (?, ?, ?) Hibernate: update Student set BRANCH_ID=? where id=? Nov 19, 2020 10:55:19 AM org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure ERROR: HHH000346: Error during managed flush [org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance beforeQuery flushing: com.javabydeveloper.domain.Student] javax.persistence.RollbackException: Error while committing the transaction at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:75) at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:71) at com.javabydeveloper.App.main(App.java:43) Caused by: java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance beforeQuery flushing: com.javabydeveloper.domain.Student at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:144) at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155) at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162) at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1434) at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:484) at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3190) at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2404) at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220) at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68) ... 1 more Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance beforeQuery flushing: com.javabydeveloper.domain.Student at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:279) at org.hibernate.type.EntityType.getIdentifier(EntityType.java:462) at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:151) at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:894) at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1317) at org.hibernate.persister.collection.OneToManyPersister.recreate(OneToManyPersister.java:186) at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:50) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:586) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:460) at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337) at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39) at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428) ... 9 more
2. Understanding Root Cause
Hibernate first inserted Branch record in database and trying to update foreign key BRANCH_ID in Student table. But Student record not yet inserted in DB. Which means, the Student entity state is transient in Persistence Context.
So, Branch object has reference (Student), which is an unsaved transient instance. We need to save Student (transient instance) before Hibernate flushing Branch.
3. Solution
In Hibernate, In Parent and Child table association mappings, this is a common issue. To fix the issue, we need to apply proper Cascading operation to the reference in Branch entity using CascadeType.
CascadeType propagates entity transitions from Parent to Child. For example, if you persist parent entity the referenced entities also get persisted before flushing. Let’s update the Branch entity using CascadeType.ALL.
@Entity public class Branch implements Serializable { @Id @Column(name="BRANCH_ID") private int branchId; @Column(name="BRANCH_NAME") private String branchName; @Column(name="BRANCH_SHORT_NAME") private String branchShortName; private String description; //uni-directional one-to-many association to Student @OneToMany(cascade = CascadeType.ALL , orphanRemoval = true) @JoinColumn(name="BRANCH_ID") private List<Student> students; // .. omitted setters getters etc. }
Let’s run the program again and verify results.
Hibernate: insert into Branch (BRANCH_NAME, BRANCH_SHORT_NAME, description) values (?, ?, ?) Hibernate: insert into Student (CONTACT_NO, fname, lname) values (?, ?, ?) Hibernate: insert into Student (CONTACT_NO, fname, lname) values (?, ?, ?) Hibernate: update Student set BRANCH_ID=? where id=? Hibernate: update Student set BRANCH_ID=? where id=? Nov 19, 2020 11:21:43 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
Now, we can notice Student records get updated before updating BRANCH_ID foreign key in Student table.
4. Conclusion
We have seen the root cause of issue “object references an unsaved transient instance – save the transient instance beforeQuery flushing” in JPA with Hibernate and how to fix the issue.
5. References
- Hibernate One-To-Many
- org.hibernate.TransientPropertyValueException
Fix for “object references an unsaved transient instance – save the transient instance beforeQuery flushing” in Hibernate
When I am working with association in JPA with Hibernate, Error during managed flush [org.hibernate.TransientObjectException: object references an unsaved transient instance – save the transient instance beforeQuery flushing …] is one of the common error often I have seen.
Lets’s see when this Error occur and how to fix this issue. First let’s reproduce the issue.
1. Reproducing Issue
Entity Mappings:
Let’s save Branch entity.
Output:
We will get ERROR: HHH000346: Error during managed flush [org.hibernate.TransientObjectException: object references an unsaved transient instance – save the transient instance beforeQuery flushing: com.javabydeveloper.domain.Student]
2. Understanding Root Cause
Hibernate first inserted Branch record in database and trying to update foreign key BRANCH_ID in Student table. But Student record not yet inserted in DB. Which means, the Student entity state is transient in Persistence Context.
So, Branch object has reference (Student), which is an unsaved transient instance. We need to save Student (transient instance) before Hibernate flushing Branch.
3. Solution
In Hibernate, In Parent and Child table association mappings, this is a common issue. To fix the issue, we need to apply proper Cascading operation to the reference in Branch entity using CascadeType.
CascadeType propagates entity transitions from Parent to Child. For example, if you persist parent entity the referenced entities also get persisted before flushing. Let’s update the Branch entity using CascadeType.ALL.
Let’s run the program again and verify results.
Now, we can notice Student records get updated before updating BRANCH_ID foreign key in Student table.
4. Conclusion
We have seen the root cause of issue “object references an unsaved transient instance – save the transient instance beforeQuery flushing” in JPA with Hibernate and how to fix the issue.
Источник
Statement batch of session not cleared on transaction rollback #991
Comments
bassmartin commented Aug 23, 2017 •
Overview
I’m using Spring Retry to re-attempt transactions of a REST endpoint (mainly to retry when there is a StaleStateException).
When a StaleStateException happens on the first attempt of the transaction to modify the name of a Person domain instance, there is a statement batch with the failing update SQL that gets linked to the Hibernate Session injected in the controller’s action.
On subsequent attempts (that should successfully update the Person instance since the instance is reloaded from the DB), it fails during commit since the old update statement is still in the statement batch associated to the Session.
Steps to Reproduce
- Run teststatementbatch.PersonServiceIntegrationSpec of the provided example
- Look at the printed logs for the exception thrown during the commit
Expected Behaviour
I would expect that the transaction rollback that is happening on the first attempt to update the name of the Person would clear the Session (as it does) and also the associated statement batch so that the second attempt to update the Person’s name works.
Actual Behaviour
The statement batch associated to the Hibernate session is not cleared so any further attempt to commit a change to Person fails
Environment Information
- Operating System: OSX
- GORM Version: 6.0.12.RELEASE
- Grails Version (if using Grails): 3.2.11
- JDK Version: jdk1.8.0_111
Example Application
The text was updated successfully, but these errors were encountered:
Источник
Hibernate — @ElementCollection — Странное поведение удаления / вставки
Учитывая следующую структуру классов, когда я пытаюсь добавить новое местоположение в список локаций Person, это всегда приводит к следующим SQL-запросам:
Hibernate (3.5.x/JPA 2) удаляет все связанные записи для данного Person и повторно вставляет все предыдущие записи, а также новый.
У меня возникла идея, что метод equals/hashcode на Location разрешит проблему, но ничего не изменит.
Любые подсказки оценены!
4 ответа
Проблема как-то объясняется на странице о ElementCollection JPA wikibook:
Первичные ключи в CollectionTable
В спецификации JPA 2.0 нет предоставить способ определения Id в Embeddable . Однако для удаления или обновить элемент ElementCollection , некоторые уникальные ключ обычно требуется. В противном случае, при каждом обновлении поставщик JPA необходимо удалить все из CollectionTable для Entity и затем вставьте значения обратно. Итак, Поставщик JPA, скорее всего, предположит что комбинация всех поля в Embeddable уникальны, в сочетании с внешним ключом ( JoinColunm (ы)). Это может быть неэффективно или просто невозможно, если Embeddable является большим или сложным.
И это точно (часть жирным шрифтом), что здесь происходит (Hibernate не генерирует первичный ключ для таблицы коллекции и не имеет способа определить, какой элемент коллекции был изменен, и удалит старое содержимое из таблицы для добавления нового содержимого).
Однако , если вы определяете @OrderColumn (чтобы указать столбец, используемый для поддержания постоянного порядка списка, что будет иметь смысл, поскольку вы используете List ), Hibernate создаст первичный ключ (сделанный из столбца порядка и столбца объединения) и сможет обновить таблицу коллекций без удаления всего содержимого.
Что-то вроде этого (если вы хотите использовать имя столбца по умолчанию):
Источник
ERROR ExceptionMapperStandardImpl HHH000346: Error during managed flush
[org.hibernate.TransientObjectException:
object references an unsaved transient instance - save the
transient instance before flushing: cao.domain.User]
java.lang.IllegalStateException: org.hibernate.
TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: cao.domain.User
Эта ошибка обычно происходит во многих, многие в
Эта ошибка означает, что другая таблица, связанная с клавишей лба, не сохраняется (нет набора), либо сохранена - это нулевое значение.
Например: Я вот «пользовательские записи» UserID внешних ключевых постов, связанные с пользователем пользователя, когда пользователь входит в систему, пользователь, хранящийся на сеансе, получает пользователь, хранящийся на сеансе, когда пользовательские публикации, здесь я приобретающую пользователь Это нуль, поэтому пост внешнего ключа — это нуль, поэтому я здесь, чтобы установить UserID не может быть нулевой ошибкой
Справка Проверьте таблицу, связанную с другим столом, следует ли сохранять (настройку) в процессе таблицы
When I try to run my test class, I get this error below. I do not know what to do anymore, when I comment on the FOLDERAUTOUPDATE
attribute of the class ApplicationItv
the insertion works in the bank, however I need it.
Can anyone help me?
INFO: HHH000400: Using dialect: org.hibernate.dialect.OracleDialect
dez 10, 2018 8:35:00 AM org.hibernate.dialect.Oracle9Dialect <init>
WARN: HHH000063: The Oracle9Dialect dialect has been deprecated; use either Oracle9iDialect or Oracle10gDialect instead
dez 10, 2018 8:35:00 AM org.hibernate.dialect.OracleDialect <init>
WARN: HHH000064: The OracleDialect dialect has been deprecated; use Oracle8iDialect instead
Hibernate:
select
SEQ_APPLICATION_ITV.nextval
from
dual
Hibernate:
insert
into
APPLICATION_ITV
(bandWidth, folderAutoUpdate, name, who, id)
values
(?, ?, ?, ?, ?)
dez 10, 2018 8:35:01 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 904, SQLState: 42000
dez 10, 2018 8:35:01 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-00904: "FOLDERAUTOUPDATE": identificador inválido
dez 10, 2018 8:35:01 AM org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.SQLGrammarException: could not execute statement]
Falha no banco de dados:
ORA-00904: "FOLDERAUTOUPDATE": identificador inválido
The database for this table:
ThepersistenceXML:
<persistenceversion="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="bancoItv">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>br.com.sky.iTvMC.modelo.ApplicationItv</class>
<class>br.com.sky.iTvMC.modelo.AppointmentCategory</class>
<class>br.com.sky.iTvMC.modelo.Bit</class>
<class>br.com.sky.iTvMC.modelo.Channel</class>
<class>br.com.sky.iTvMC.modelo.ChannelCategory</class>
<class>br.com.sky.iTvMC.modelo.City</class>
<class>br.com.sky.iTvMC.modelo.ClientChannel</class>
<class>br.com.sky.iTvMC.modelo.ClientChannelAppointment</class>
<class>br.com.sky.iTvMC.modelo.Image</class>
<class>br.com.sky.iTvMC.modelo.ImageCategory</class>
<class>br.com.sky.iTvMC.modelo.Segmentation</class>
<class>br.com.sky.iTvMC.modelo.SegmentationRules</class>
<class>br.com.sky.iTvMC.modelo.Video</class>
<class>br.com.sky.iTvMC.modelo.VideoArtist</class>
<class>br.com.sky.iTvMC.modelo.VideoCategory</class>
<properties>
<!-- Propriedades JDBC -->
<property name="javax.persistence.jdbc.driver"
value="oracle.jdbc.OracleDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:oracle:thin:@10.16.2.30:1521:apps" />
<property name="javax.persistence.jdbc.user" value="itv" />
<property name="javax.persistence.jdbc.password" value="itvsky2015"
/>
<!-- Configuracoes especificas do Hibernate -->
<property name="hibernate.dialect"
value="org.hibernate.dialect.OracleDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<!-- poderia ser: update, create, create-drop, none -->
<property name="hibernate.hbm2ddl.auto" value="none" />
</properties>
</persistence-unit>
</persistence>
My DAO:
package br.com.sky.iTvMC.dao;
import java.util.List;
import javax.persistence.EntityManager;
import br.com.sky.iTvMC.modelo.ApplicationItv;
public class ApplicationItvDao {
private EntityManager manager;
public ApplicationItvDao(EntityManager manager) {
this.manager = manager;
}
public void add(ApplicationItv applicationItv) {
this.manager.persist(applicationItv);
}
public void remove(ApplicationItv applicationItv) {
this.manager.remove(applicationItv);
}
public void update(ApplicationItv applicationItv) {
this.manager.merge(applicationItv);
}
public ApplicationItv find(Integer id) {
return this.manager.find(ApplicationItv.class, id);
}
public List<ApplicationItv> list() {
return this.manager.createQuery("SELECT * FROM APPLICATION_ITV",
ApplicationItv.class).getResultList();
}
}
My Test Class:
package br.com.sky.iTvMC.teste;
import javax.persistence.EntityManager;
import br.com.sky.iTvMC.dao.ApplicationItvDao;
import br.com.sky.iTvMC.modelo.ApplicationItv;
import br.com.sky.iTvMC.util.*;
public class testandoApplicationItv {
public static void main(String[] args) {
try {
EntityManager manager = new JPAUtil().getEntityManager();
ApplicationItvDao dao = new ApplicationItvDao(manager);
ApplicationItv applicationItv = new ApplicationItv();
applicationItv.setName("Canal do cliente HD");
applicationItv.setBandWidth(230);
applicationItv.setFolderAutoUpdate("pasta/teste");
applicationItv.setWho("funcionaroio");
manager.getTransaction().begin();
dao.add(applicationItv);
manager.getTransaction().commit();
manager.close();
System.out.println(applicationItv);
} catch (Exception e) {
BDUtil bdUtil = new BDUtil();
bdUtil.trataSQLException(e);
}
}
}
My Class Model:
package br.com.sky.iTvMC.modelo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Table(name = "APPLICATION_ITV")
@Entity
public class ApplicationItv {
@SequenceGenerator(name = "seqAppItv", sequenceName = "SEQ_APPLICATION_ITV",
allocationSize = 1)
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqAppItv")
private Integer id;
private String name;
private Integer bandWidth;
private String folderAutoUpdate;
private String who;
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getBandWidth() {
return bandWidth;
}
public void setBandWidth(Integer bandWidth) {
this.bandWidth = bandWidth;
}
public String getFolderAutoUpdate() {
return folderAutoUpdate;
}
public void setFolderAutoUpdate(String folderAutoUpdate) {
this.folderAutoUpdate = folderAutoUpdate;
}
}
asked by
anonymous 10.12.2018 / 11:39