简体   繁体   中英

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

在此输入图像描述

here is what i want

在此输入图像描述

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

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.

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?

您应该使用distinct关键字来过滤相同的结果。

您的实体Myview必须实现java.io.Serializable接口

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

将Hibernate返回的对象放到LinkedHashSet并返回LinkedHashSet。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM