Hibernate - batch update returned unexpected line count from update: 0 actual number of lines: 0 expected: 1

I get the following sleeping error. I can identify the function that causes the problem. Unfortunately, the function has several database calls. I cannot find the line that causes the problem, since hibernate ends the session at the end of the transaction. The following sleep error looks like a general error. It does not even mention which Bean is causing the problem. Anyone familiar with this sleep error?

org.hibernate.StaleStateException: Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1 at org.hibernate.jdbc.BatchingBatcher.checkRowCount(BatchingBatcher.java:93) at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:79) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:58) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:195) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:142) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:297) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:985) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:333) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:584) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransacti onManager.java:500) at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManag er.java:473) at org.springframework.transaction.interceptor.TransactionAspectSupport.doCommitTransactionAfterReturning(Transaction AspectSupport.java:267) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:170) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:176) 
+125
java hibernate
Apr 30 '10 at 8:11
source share
30 answers

Without code and mappings for your transactions, it is almost impossible to investigate the problem.

However, to better understand the cause of the problem, try the following:

  • In your hibernate configuration, set hibernate.show_sql to true. This should show you the SQL that is executing and causing the problem.
  • Set the log levels for Spring and Hibernate for DEBUG, this will give you a better idea of ​​which line is causing the problem.
  • Create a unit test that replicates the problem without setting up a transaction manager in Spring. This should give you a better idea of ​​code violation.

Hope this helps.

+53
Apr 30 '10 at 9:55
source share

I got the same exception by deleting the record with an identifier that does not exist at all. So check that the record you are updating / Deleting actually exists in DB

+62
Nov 09
source share

Solution: In the Hibernate mapping file for the id property, if you use any generator class, you should not explicitly set the value for this property using the setter method.

If you set the value of the Id property explicitly, this will result in the error above. Check this to avoid this error. or This error shows when you specify the field generator = "native" or "incremental" in the mapping file, and in your database the table displayed is not an auto_incremented solution. Go to your database and refresh the table to set auto_increment

+48
May 07 '14 at 16:18
source share

This happened to me once when I assigned certain identifiers to certain objects (testing), and then I tried to store them in a database. The problem was that the database had a specific policy for creating object identifiers. Just do not assign an identifier if you have a policy at the Hibernate level.

+17
Apr 17 '14 at 23:58
source share

In my case, I came to this exception in two similar cases:

  • In the method annotated by @Transactional I had a call to another service (with a long response time). The method updates some properties of the object (after the method, the object still exists in the database). If the user requests the method twice (since he believes that he is not working for the first time) when he leaves the transaction method for the second time, Hibernate tries to update an entity that has already changed its state from the beginning of the transaction. When Hibernate searches for an entity in state and discovers the same entity, but already modified by the first request, it throws an exception, because it cannot update the entity. This is like a conflict in the digestive tract.
  • I had automatic queries (to monitor the platform) that update the entity (and manual rollback in a few seconds). But this platform is already used by the test team. When a tester runs a test in the same entity as automatic queries (within one hundredth of a millisecond), I get an exception. As in the previous case, when you exit the second transaction, the previously extracted object has already changed.

Conclusion: in my case, this was not a problem that can be found in the code. This exception is thrown when Hibernate discovers that an entity that was first retrieved from the database changed during the current transaction , so it cannot dump it into the database because Hibernate does not know which version of the entity is correct: the current selection of the transaction at the beginning; or one that is already stored in the database.

Solution: to solve the problem, you will have to play with Hibernate LockMode to find the one that best suits your requirements.

+10
Oct 28 '17 at 12:20
source share

This can happen when a trigger executes additional DML (data change) queries that affect the number of rows. My solution was to add the following at the top of my trigger:

 SET NOCOUNT ON; 
+9
Feb 11 '14 at 15:44
source share

I just ran into this problem and found that I was deleting the record and trying to update it later in the Hibernate transaction.

+8
Feb 08 '13 at 12:19
source share

I faced the same problem. The code worked in a test environment. But he did not work in an intermediate environment.

 org.hibernate.jdbc.BatchedTooManyRowsAffectedException: Batch update returned unexpected row count from update [0]; actual row count: 3; expected: 1 

The problem was that the table had one record for each primary key when testing the database table. But in the intermediate database there were several records for the same primary key. (The problem is in the intermediate database, there were no primary key restrictions in the table, there were also several records.)

Therefore, each time it updates, it receives a failure. He tries to update one record and expect the number of updates to be 1. But since there were 3 records for the same primary key, the number of update results is 3. Since the expected number of updates and the actual update result do not match, he throws an exception and rolls back.

After I deleted all the records that have a duplicate primary key and added the primary key constraints. It is working fine.

 Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1 

actual number of rows: 0 // means that no record was found to update
update: 0 // means that the record was not found, so nothing is updated
Expected: 1 // means that at least 1 record with a key in the db table is expected.

The problem here is that the request is trying to update the record for some key, but hibernate could not find the record with the key.

+6
Aug 25 '15 at 10:03
source share

I ran into this problem when we had a one-to-many relationship.

In the hibm hibm mapping file for master, cascade="save-update" added for the object with the set type setting, and it worked fine.

Without this, by default, hibernate tries to update a nonexistent record and thereby inserts instead.

+5
May 01 '14 at 3:37
source share

As Julius says, this happens when an update occurs on an object in which its children are deleted. (Perhaps because there was a need to update for the entire object of the Father, and sometimes we prefer to remove the children and re-insert them into the Father (new, old does not matter) along with any other updates that the father could have on any of his other plains fields) So ... for this to work, delete the children (inside the transaction) by calling childrenList.clear() (Dont scroll through the children and delete each one with childDAO.delete(childrenList.get(i).delete())) and @OneToMany(cascade = CascadeType.XXX ,orphanRemoval=true) settings @OneToMany(cascade = CascadeType.XXX ,orphanRemoval=true) on the side of the Father's object. Then update the father (fatherDAO.update (father)). (Repeat for each father object). As a result, children are attached to their father, and then they are removed as orphans using a frame.

+4
Aug 29 '13 at 18:50
source share

This can also happen when you try to update the UPDATE key .

+4
Aug 31 '17 at 17:09 on
source share

I have the same problem and I confirmed that this could happen due to the automatic increase of the primary key. To solve this problem, do not insert the value of the automatic growth with the data set. Insert data without primary key.

+3
Apr 30 '14 at 9:36
source share

Another way to get this error is if you have a null item in the collection.

+3
Oct 19 '18 at 19:14
source share

this will happen when you try to delete the same object, and then refresh the same object that is used after the deletion

session.clear ();

+2
Oct 17 '13 at 8:47
source share

This happened to me because I had my Long identifier, and I was getting 0 from the view, and when I tried to save to the database, I got this error, then fixed it by setting id to null.

+2
Feb 16 '15 at 23:37
source share

I ran into this problem when I started manually and committed transactions inside a method annotated as @Transactional . I fixed the problem by finding that an active transaction already exists.

 //Detect underlying transaction if (session.getTransaction() != null && session.getTransaction().isActive()) { myTransaction = session.getTransaction(); preExistingTransaction = true; } else { myTransaction = session.beginTransaction(); } 

Then I let Spring handle the transaction.

 private void finishTransaction() { if (!preExistingTransaction) { try { tx.commit(); } catch (HibernateException he) { if (tx != null) { tx.rollback(); } log.error(he); } finally { if (newSessionOpened) { SessionFactoryUtils.closeSession(session); newSessionOpened = false; maxResults = 0; } } } } 
+1
Oct 06 '14 at 15:42
source share

This happens when you declared the JSF Managed Bean as

 @RequestScoped; 

when you should declare how

 @SessionScoped; 

Hello;

+1
Jul 30 '15 at 22:05
source share

I got this error when I tried to update an object with an identifier that was not in the database. The reason for my error was that I manually assigned a property with the name “id” to the client-side JSON representation of the client, and then when deserializing the object on the server side, this “id” property would replace the instance variable (also called “id”), which was supposed to generate hibernate. Therefore, be careful with collision names if you use Hibernate to generate identifiers.

+1
May 11 '16 at 9:12
source share

I also faced the same challenge. In my case, I was updating an object that didn't even exist using hibernateTemplate .

In fact, in my application, I was getting a database object to update. And, updating its values, I also mistakenly updated its identifier and went on to update it and came across the indicated error.

I am using hibernateTemplate for CRUD operations.

+1
Jul 17 '16 at 18:10
source share

After reading all the answers, there was no one who could talk about the inverse attribute of sleep mode.

In my opinion, you should also check in your relationship whether the reverse keyword is set correctly. The converse is designed to determine which party owns the relationship. The update and insertion procedure depends on this attribute.

Suppose we have two tables:

main_table , middle_table

with a ratio of one to many . The hiberntate mapping classes are Primary and Secondary, respectively.

So, the Principal class has a SET of Medium objects. The xml mapping file should look like this:

 <hibernate-mapping> <class name="path.to.class.Principal" table="principal_table" ...> ... <set name="middleObjects" table="middle_table" inverse="true" fetch="select"> <key> <column name="PRINCIPAL_ID" not-null="true" /> </key> <one-to-many class="path.to.class.Middel" /> </set> ... 

The inverse value is set to true, which means that the middle class is the owner of the relationship, so the Principal class will be NOT UPDATE .

So, the update procedure can be implemented as follows:

 session.beginTransaction(); Principal principal = new Principal(); principal.setSomething("1"); principal.setSomethingElse("2"); Middle middleObject = new Middle(); middleObject.setSomething("1"); middleObject.setPrincipal(principal); principal.getMiddleObjects().add(middleObject); session.saveOrUpdate(principal); session.saveOrUpdate(middleObject); // NOTICE: you will need to save it manually session.getTransaction().commit(); 

It worked for me, you can suggest some editions to improve the solution. So we will all learn.

+1
Aug 21 '16 at 14:33
source share

This happened if you changed something in the dataset using your own SQL query, but a persistent object for the same dataset is present in the session cache. Use session.evict (yourObject);

0
Jun 22 '16 at 0:32
source share

Sleep mode caches objects from the session. If the object is accessible and modified by more than one user, then org.hibernate.StaleStateException can be org.hibernate.StaleStateException . It can be solved using the merge / update object method before saving or using a lock. Additional information: http://java-fp.blogspot.lt/2011/09/orghibernatestalestateexception-batch.html

0
Aug 11 '16 at
source share

One of the cases

 SessionFactory sf=new Configuration().configure().buildSessionFactory(); Session session=sf.openSession(); UserDetails user=new UserDetails(); session.beginTransaction(); user.setUserName("update user agian"); user.setUserId(12); session.saveOrUpdate(user); session.getTransaction().commit(); System.out.println("user::"+user.getUserName()); sf.close(); 
0
Sep 12 '16 at 6:15
source share

I got this error because I mistakenly matched the ID column using Id(x => x.Id, "id").GeneratedBy.**Assigned**();

The problem is resolved using Id(x => x.Id, "id").GeneratedBy.**Identity**();

0
Nov 28 '16 at 11:34
source share

I came across this exception and sleep mode worked well. I tried to manually insert one entry using pgAdmin, here the problem became apparent. SQL insert query returns 0 insert. and there is a trigger function that causes this problem, since it returns null. so I only have to set it to return a new one. and finally i solved the problem.

Hope this helps any body.

0
03 Mar. '17 at 15:38
source share

This happens to me because I miss the id declaration in the bean class.

0
Jan 16 '18 at 12:50
source share

In my case, there was a problem with the database, since one of the stored processors consumed the entire processor, causing a large database response time. Once it was killed, the problem was resolved.

0
02 Feb '18 at 7:17
source share

Actually, this happened to me when I did not save the object as a reference variable. in an entity class. Liked this code: ses.get(InsurancePolicy.class, 101); After that I saved the object in the entity reference variable, so the problem was solved for me. policy=(InsurancePolicy)ses.get(InsurancePolicy.class, 101); After that I updated the object and it worked fine.

0
Mar 02 '18 at 17:51
source share

I received the same message. After searching for the source code associated with the code, it occurred to me that running the application on the local computer interferes with the development phase, since the shared resource matches the database. Therefore, sometimes one server already deleted the record, and the other just wanted to do the same.

0
Jul 16 '18 at 8:34
source share

Several ways to debug this error:

  1. As suggested in the accepted answer- enable sql show.
  2. I found that there are some problems with setting the identifier in Hibernate SQL.
  3. Found that I'm missing @GeneratedValue (strategies = GenerationType.IDENTITY)
0
Jan 16 '19 at 9:45
source share



All Articles