Muhammad Salman Farooq
Muhammad Salman Farooq

Reputation: 1325

Hibernate query gives same record multiple times

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

Upvotes: 23

Views: 17613

Answers (6)

Koray Tugay
Koray Tugay

Reputation: 23844

Put the objects returned by Hibernate to a LinkedHashSet and return the LinkedHashSet.

Upvotes: 0

Saif
Saif

Reputation: 7052

If you have association in the mapping then check if fetch=FetchType.EAGER. If yes then use other fetch type or fetchMode.

Upvotes: -1

martin.hatas
martin.hatas

Reputation: 11

Your entity Myview have to implement java.io.Serializable interface

Upvotes: 0

shridharama
shridharama

Reputation: 979

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.

Upvotes: 40

user1112699
user1112699

Reputation: 197

You should use the distinct keyword to filter the same result.

Upvotes: 1

Heetola
Heetola

Reputation: 6191

Are you sure that the table is correctly filled? try :

List list = sess1.createQuery("SELECT * FROM Myview").list();

futhermore, you are getting this list from a view? are you sure that you made this view correctly?

Upvotes: 0

Related Questions