Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate, getting duplicate values

I am writing a very simple query, but I am getting duplicate values for some reason.

Criteria cr = session.createCriteria(ProcessInstance.class, "p")
        .add(Restrictions.isNull("end"));
@Cleanup ScrollableResults sr = cr.scroll(ScrollMode.FORWARD_ONLY);

while (sr.next()) {
    pi = (ProcessInstance) sr.get(0);
    String id = pi.getId(); //Getting duplicate values
}

The pi.getId() returns duplicate values. ie: *9,9,10,10,11,11 etc*

However, running this query directly in mysql

SELECT * FROM JBPM_PROCESSINSTANCE J where J.END_ IS NULL

Does not return duplicate values.

Can anyone spot what is wrong?

like image 294
Shervin Asgari Avatar asked Jan 10 '11 09:01

Shervin Asgari


People also ask

Why does JPA return duplicate rows?

Issue with @Id column, If we check closely, @Id column value is same for all the rows. Hence hibernate/JPA not able to get different records, it just get 1st record with this @Id and return duplicate records of it. Solution - Use @IdClass with columns which result in unique row instead of duplicate row.

How can we avoid inserting duplicate records in mysql using Java?

The easiest way is to designate the primary key as UNIQUE. Be sure to check the return value of your insert commands as then the server will reject the duplicates.


1 Answers

The fast workarround would be to use a Distinct Root Entity Result Transformer.

...
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List unique = crit.List();
...

But this is only a workarround.

I ques the problem belongs to your mapping. If there is any eager loaded 1:n relationship from ProcessInstance to something else (call it X), and there are several (n) X for one ProcessInstance, the you will get several ProcessInstance items (n) in the result list for a single ProcessInstance. -- If this is realy the cause, than the workarround is not just a workarround, then it would be the solution.

like image 116
Ralph Avatar answered Oct 03 '22 09:10

Ralph