최대 절전 모드-일괄 업데이트가 업데이트에서 예기치 않은 행 개수를 반환했습니다. 0 실제 행 개수 : 0 예상 : 1
최대 절전 모드 오류가 발생합니다. 문제를 일으키는 기능을 식별 할 수 있습니다. 불행히도 함수에는 여러 DB 호출이 있습니다. 최대 절전 모드에서 트랜잭션 종료시 세션을 플러시하므로 문제를 일으키는 줄을 찾을 수 없습니다. 아래에 언급 된 최대 절전 모드 오류는 일반적인 오류처럼 보입니다. 어떤 Bean이 문제를 일으키는 지 언급하지 않았습니다. 이 최대 절전 모드 오류에 익숙한 사람이 있습니까?
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)
트랜잭션에 대한 코드 및 매핑이 없으면 문제를 조사하는 것이 불가능할 것입니다.
그러나 문제의 원인을 더 잘 처리하려면 다음을 시도하십시오.
- 최대 절전 모드 구성에서 hibernate.show_sql을 true로 설정하십시오. 실행되고 문제를 일으키는 SQL이 표시됩니다.
- Spring 및 Hibernate의 로그 레벨을 DEBUG로 설정하십시오. 다시 말하면 어느 라인이 문제를 일으키는 지 더 잘 알 수 있습니다.
- Spring에서 트랜잭션 관리자를 구성하지 않고 문제점을 복제하는 단위 테스트를 작성하십시오. 이렇게하면 문제가되는 코드 줄을 더 잘 이해할 수 있습니다.
희망이 도움이됩니다.
전혀 존재하지 않는 ID로 레코드를 삭제하는 동안 동일한 예외가 발생했습니다. 따라서 업데이트 / 삭제중인 레코드가 실제로 DB에 존재하는지 확인하십시오.
솔루션 : id 속성에 대한 최대 절전 모드 매핑 파일에서 생성기 클래스를 사용하는 경우 해당 속성에 대해 setter 메서드를 사용하여 명시 적으로 값을 설정해서는 안됩니다.
Id 속성 값을 명시 적으로 설정하면 위의 오류가 발생합니다. 이 오류를 피하려면 이것을 확인하십시오. 또는 맵핑 파일에서 필드 generator = "native"또는 "incremental"을 언급하고 DATABASE에서 맵핑 된 테이블이 자동 증가하지 않습니다. 해결책 : DATABASE로 이동하여 테이블을 업데이트하여 auto_increment를 설정하십시오.
일부 객체에 특정 ID를 할당 (테스트)하고 데이터베이스에 저장하려고 할 때 우연히 한 번 발생했습니다. 문제는 데이터베이스에 개체의 ID를 설정하기위한 특정 정책이 있다는 것입니다. 그냥 하지 않습니다 당신이 최대 절전 모드 수준에서 정책이있을 경우 ID를 할당합니다.
이는 트리거가 행 수에 영향을주는 추가 DML (데이터 수정) 쿼리를 실행할 때 발생할 수 있습니다. 내 솔루션은 트리거의 맨 위에 다음을 추가하는 것이 었습니다.
SET NOCOUNT ON;
필자의 경우 비슷한 두 가지 경우 에이 예외가 발생했습니다.
- 주석이 달린 메소드
@Transactional
에서 다른 서비스에 대한 호출이있었습니다 (긴 응답 시간). 이 메소드는 엔티티의 일부 특성을 업데이트합니다 (메소드 후에 엔티티가 여전히 데이터베이스에 존재 함). 트랜잭션 메소드에서 두 번째 종료 할 때 사용자가 메소드를 두 번 요청하면 (처음으로 작동하지 않는다고 생각하는 경우) Hibernate는 트랜잭션 시작에서 상태를 이미 변경 한 엔티티를 업데이트하려고 시도합니다. 최대 절전 모드에서는 상태의 엔터티를 검색하고 동일한 엔터티를 찾았지만 첫 번째 요청에 의해 이미 변경되었으므로 엔터티를 업데이트 할 수 없으므로 예외가 발생합니다. GIT의 충돌과 같습니다. - 엔티티를 업데이트하는 자동 요청 (플랫폼 모니터링)과 몇 초 후에 수동 롤백이있었습니다. 그러나이 플랫폼은 이미 테스트 팀에서 사용하고 있습니다. 테스터가 자동 요청과 동일한 엔터티에서 동일한 백분의 1 밀리 초 내에 테스트를 수행하면 예외가 발생합니다. 이전 경우와 마찬가지로, 두 번째 트랜잭션을 종료 할 때 이전에 가져온 엔티티가 이미 변경되었습니다.
결론 : 제 경우에는 코드에서 찾을 수있는 문제가 아닙니다. 이 예외는 Hibernate가 현재 트랜잭션 중에 데이터베이스에서 처음으로 가져온 엔티티가 변경된 것을 발견했을 때 발생 하므로 Hibernate가 엔티티의 올바른 버전을 알지 못하므로 데이터베이스로 플러시 할 수 없습니다. 처음에 트랜잭션 가져 오기; 또는 이미 데이터베이스에 저장된 것입니다.
해결 방법 : 문제를 해결하기 위해, 당신은 최대 절전 모드로 플레이해야합니다 의 LockMode 가장 귀하의 요구 사항에 맞는 하나를 찾을 수 있습니다.
방금이 문제가 발생하여 레코드를 삭제하고 나중에 Hibernate 트랜잭션에서 업데이트하려고한다는 것을 알았습니다.
I was facing same issue. The code was working in the testing environment. But it was not working in staging environment.
org.hibernate.jdbc.BatchedTooManyRowsAffectedException: Batch update returned unexpected row count from update [0]; actual row count: 3; expected: 1
The problem was the table had single entry for each primary key in testing DB table. But in staging DB there was multiple entry for same primary key. ( Problem is in staging DB the table didn't had any primary key constraints also there was multiple entry.)
So every time on update operation it gets failed. It tries to update single record and expect to get update count as 1. But since there was 3 records in the table for the same primary key, The result update count finds 3. Since expected update count and actual result update count didn't match, It throws exception and rolls back.
After the I removed all the records which have duplicate primary key and added primary key constraints. It is working fine.
Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1
actual row count: 0 // means no record found to update
update: 0 // means no record found so nothing update
expected: 1 // means expected at least 1 record with key in db table.
Here the problem is that the query trying to update a record for some key, But hibernate didn't find any record with the key.
I encountered this problem where we had one-many relationship.
In the hibernate hbm mapping file for master, for object with set type arrangement, added cascade="save-update"
and it worked fine.
Without this, by default hibernate tries to update for a non-existent record and by doing so it inserts instead.
As Julius says this happens when an update Occurs on an Object that has its children being deleted. (Probably because there was a need for an update for the whole Father Object and sometimes we prefer to delete the children and re -insert them on the Father (new , old doesnt matter )along with any other updates the father could have on any of its other plain fields) So ...in order for this to work delete the children (within a Transaction) by calling childrenList.clear()
(Dont loop through the children and delete each one with some childDAO.delete(childrenList.get(i).delete()))
and setting @OneToMany(cascade = CascadeType.XXX ,orphanRemoval=true)
on the Side of the Father Object. Then update the father (fatherDAO.update(father)). (Repeat for every father object) The result is that children have their link to their father stripped off and then they are being removed as orphans by the framework.
It also can happen when you try to UPDATE
a PRIMARY KEY.
i got the same problem and i verified this may occur because of Auto increment primary key. To solve this problem do not inset auto increment value with data set. Insert data without the primary key.
Another way to get this error is if you have a null item in a collection.
its happen when you try to delete the same object and then again update the same object use this after delete
session.clear();
This happened to me too, because I had my id as Long, and I was receiving from the view the value 0, and when I tried to save in the database I got this error, then I fixed it by set the id to null.
I ran into this issue when I was manually beginning and committing transactions inside of method annotated as @Transactional
. I fixed the problem by detecting if an active transaction already existed.
//Detect underlying transaction
if (session.getTransaction() != null && session.getTransaction().isActive()) {
myTransaction = session.getTransaction();
preExistingTransaction = true;
} else {
myTransaction = session.beginTransaction();
}
Then I allowed Spring to handle committing 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;
}
}
}
}
This happens when you declared the JSF Managed Bean as
@RequestScoped;
when you should declare as
@SessionScoped;
Regards;
I got this error when I tried to update an object with an id that did not exist in the database. The reason for my mistake was that I had manually assigned a property with the name 'id' to the client side JSON-representation of the object and then when deserializing the object on the server side this 'id' property would overwrite the instance variable (also called 'id') that Hibernate was supposed to generate. So be careful of naming collisions if you are using Hibernate to generate identifiers.
I also came across the same challenge. In my case I was updating an object which was not even existing, using hibernateTemplate
.
Actually in my application I was getting a DB object to update. And while updating its values, I also updated its ID by mistake, and went ahead to update it and came across the said error.
I am using hibernateTemplate
for CRUD operations.
After reading all answers did´t find anyone to talk about inverse atribute of hibernate.
In my my opinion you should also verify in your relationships mapping whether inverse key word is appropiately setted. Inverse keyword is created to defines which side is the owner to maintain the relationship. The procedure for updating and inserting varies cccording to this attribute.
Let's suppose we have two tables:
principal_table, middle_table
with a relationship of one to many. The hiberntate mapping classes are Principal and Middle respectively.
So the Principal class has a SET of Middle objects. The xml mapping file should be like following:
<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>
...
As inverse is set to ”true”, it means “Middle” class is the relationship owner, so Principal class will NOT UPDATE the relationship.
So the procedure for updating could be implemented like this:
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();
This worked for me, bu you can suggest some editions in order to improve the solution. That way we all will be learning.
This happened if you change something in data set using native sql query but persisted object for same data set is present in session cache. Use session.evict(yourObject);
Hibernate caches objects from the session. If object is accessed and modified by more than 1 user then org.hibernate.StaleStateException
may be be thrown. It may be solved with merge/refresh entity method before saving or using lock. More info: http://java-fp.blogspot.lt/2011/09/orghibernatestalestateexception-batch.html
One of the case
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();
I was facing this exception, and hibernate was working well. I tried to insert manually one record using pgAdmin, here the issue became clear. SQL insert query returns 0 insert. and there is a trigger function that cause this issue because it returns null. so I have only to set it to return new. and finally I solved the problem.
hope that helps any body.
I got this error because I mistakenly mapped the ID
column using Id(x => x.Id, "id").GeneratedBy.**Assigned**();
Issue resolved by using Id(x => x.Id, "id").GeneratedBy.**Identity**();
This happens to me because I am missing ID declaration in bean class.
In my case there was an issue with the Database as one of the Stored Procs was consuming all the CPU causing high DB response times. Once this was killed issue got resolved.
Actually, it happen to me when I didn't store the object as reference variable. in Entity class. Like this code: ses.get(InsurancePolicy.class, 101);
After that, I stored the object in entity's reference variable so problem solved for me. policy=(InsurancePolicy)ses.get(InsurancePolicy.class, 101);
After that, I updated the object and it worked fine.
I got the same message. After looking for a code related source it got to me that running the application on a local machine interferes with the dev stage, because the share the same DB. So sometimes one server has deleted an entry already while the other just wanted to do the same.
Few ways I debugged this error:
- As suggested in the accepted answer- turn on show sql.
- I found there is some issue with setting up the id in the hibernate sql.
- Found that I was missing @GeneratedValue(strategy=GenerationType.IDENTITY)
'programing tip' 카테고리의 다른 글
비교 연산자는 null int와 어떻게 작동합니까? (0) | 2020.07.07 |
---|---|
Xcode에서 "링크 된 프레임 워크"대신 "내장 바이너리"를 언제 사용해야합니까? (0) | 2020.07.07 |
IntelliJ 프로젝트 인덱스 재 구축 (0) | 2020.07.07 |
Java가 정적 초기화 블록에서 확인 된 예외를 발생시키지 않는 이유는 무엇입니까? (0) | 2020.07.06 |
GitHub 위키를 어떻게 복제합니까? (0) | 2020.07.06 |