HIbernate : More than one row with the given identifier was found

天涯浪子 提交于 2020-02-25 06:00:50

问题


@Override
    public Application getApplicationForId(Long applicationId) {

        List<Application> applications = executeNamedQuery("applicationById", Application.class, applicationId);
        return applications.isEmpty() ? null : applications.get(0);
    }

while debugging in eclipse

return applications.isEmpty() ? null : applications.get(0);

these expression getting evaluated as

applications.isEmpty() -> false

applications.get(0) -> (id=171)

applications.size() -> 1

but after the execution of this line its throwing error

org.hibernate.HibernateException: More than one row with the given identifier was found: 263536,

Even its size is showing as 1, then still why and how its getting multiple rows after the execution.


回答1:


I'm quite sure that this is due to eager fetching. So check you entity and remove the fetch=FetchType.EAGER.

Actually this is not caused by duplicate rows in the database, as it's obviously not possible to have duplicate primary keys. Instead this was caused by Hibernate looking up an object, and eagerly filling in a relationship. Hibernate assumed a single row would come back, but two came back because there were two objects associated with that relationship.




回答2:


In my case the issue was, while debugging when the execution is in the middle of the transaction, may be the purpose got served and forcibly stopped the server in the middle of the execution itself, as this has been forcibly stopped server, that cannot led the transaction to get rolledback and that end up in making the data dirty or corrupt in the database because before terminating the server some data might got inserted in db (chance of autoincrement of the primarykey). Resetting the AutoIncrement value for the primary key of the table, resolved the issue.

1.Identify the table with dirty data (refer to stack trace )

2.Sort the column(primary key), check the highest value in the column(say somevalue).

3.use command

ALTER TABLE tablename AUTO_INCREMENT = somevalue+1


来源:https://stackoverflow.com/questions/45642728/hibernate-more-than-one-row-with-the-given-identifier-was-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!