Search code examples
javasqlhibernatehibernate-criteria

Hibernate criteria returning list which contain same objects, How to resolve it?


I have written restriction as follows,

 DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
 Date frmDate= df.parse("2014-01-01");
 Date toDate=df.parse("2014-09-16");

 Criteria criteria = session.createCriteria(HistoryLatitudeBean.class);
          criteria.add(Restrictions.eq("vehicleno",12));
          criteria.add(Restrictions.ge("rdate", frmDate)); 
          criteria.add(Restrictions.lt("rdate", toDate));
          criteria.add(Restrictions.between("rdate", frmDate, toDate));

          List<HistoryLatitudeBean> groupList=criteria.list();// <---groupList contains same objects

          for(HistoryLatitudeBean hb : groupList){

              System.out.println(hb.getLat());
          }

My bean is like this,

@Entity
@Table(name="hlatlng")
public class HistoryLatitudeBean {

@Id
@Column(name="vehicleno")
private int vehicleno;
@Column(name="lat")
private String lat;
@Column(name="lng")
private String lng;
@Column(name="status")
private String status;
@Column(name="rdate")
private Date rdate;
@Column(name="rtime")
private Date rtime;

//getters and setters
}

I am trying for following query, select * from hlatlng where vehicleno=12 and rdate BETWEEN '2014-01-01' and '2014-06-05'

In DB it gives 11 rows which has diff values. When I execute it through hibernate criteria, it gives 11 objects of same value. I checked through debug in eclipse all objets in groupList same id, how can I resolve it. Please help me.


Solution

  • The issue seems to be resolved with Aleksandr M comment.

    You are missing a field annotated with @Id. Each @Entity needs an @Id - this is the primary key in the database.

    Hibernate requires an identifier for each entity.

    also, need to modify you query for omitting vehicleno since it is the primary key and will return the same result everytime.

    @Id
    @Column(name="vehicleno")
    private int vehicleno;