Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate query gives same record multiple times

Tags:

java

hibernate

I am working on hibernate in eclipse. I am executing simple 'From' query. Here is the code

  List list = sess1.createQuery("From Myview").list();
    System.out.println("Records Found :"+list.size());

    Iterator<Myview> i = list.iterator();

    while(i.hasNext())
    {
        Myview nS = i.next();
        System.out.println(nS.getFirstName()+" -- "+nS.getLastName()+" -- "+nS.getAddressLine1());
    }

The problem is the list.size() returns 11, which is right as i have 11 records in my table. But when i am in while loop, the same records shown multiple times and the loop termintes after 11th iteration. here is my output

enter image description here

here is what i want

enter image description here

Now you can see that in my output, record is displayed 11 times but the same record is repeated again and again. And what i need is the output displayed in the later image.

Kindly help me in this regard, as i am new to hibernate

like image 465
Muhammad Salman Farooq Avatar asked May 12 '12 15:05

Muhammad Salman Farooq


People also ask

Why does JPA return duplicate rows?

The issue was that the wrong column in the Instrument Entity had the @ID attribute assigned to it. I removed it from User_ID and Added it to ID and it worked fine.

How do I stop Spring Data JPA from doing a select before a save ()?

An easy way is to make your Entity implements Persistable (instead of Serializable), which will make you implement the method "isNew". The Persistable entity solution was amazing!!


1 Answers

This happens when the id element in your hbm file is not a PK in your DB table. Hibernate treats all rows with the same ID as the same object.

Either change your id element to point to a PK column or use the composite-id element in case your table only has a composite primary key.

like image 123
shridharama Avatar answered Sep 28 '22 06:09

shridharama