Problem
When using getResultList() to retrieve the Rows of the DB table there may be times where you would end up getting the same rows multiple times.
Why this Happens
Let’s have a table tblGroup the one below
ParentGrp | GrpName |
---|---|
Finance | Accounts |
Finance | Sales |
- You have 2 records in database.Both the records has Finance as value in parentGrp column
- Now when you run a select query to select parentGrp = ‘Finance’ you will get 2 records
- Lets query them WHERE parentGrp = ‘Finance’
- SQL Query returns 2 rows
- Hibernate loads first one, and puts into session, with parentGrp as a key.Now this will happen if you have specified it as @ID in entity class or you havent specified it while joining two tables in entity class.The object is placed into the result list.
- Hibernate loads second one, notices that an object with the same @Id is already in the session, and just places the reference into the result List. Row data are ignored.
- Now we have two copies of the same record
Solution:
We can solve this by introducing a primary key column something like tblGroup_pk_id.Now this helps to uniquely identify the records in the table so it won’t get overridden when the next rows retrieved.
Now the GrpId should be entitled with @ID annotation in the entity class.
GrpId | ParentGrp | GrpName |
---|---|---|
101 | Finance | Accounts |
102 | Finance | Sales |