Naresh J
Naresh J

Reputation: 2137

Add filter on oneToMany mapped table in hibernate/Spring

I am using hibernate4 and spring3.1 in my current project.

I have two tables with one to many mapping. I am using annotation based mapping. Mappings are done like this :

public class TableA {
       @Id
       private Long  id;

       @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
       @JoinColumn(name = "sample_id")
       private Set<TableB> tableBList;

       // setter getter
   }


   public class TableB{   
       @Id
       private Long                  id;

       private Long                  sample_id;

       private Date added_date;
   }

When I fired query like this :

String hql = "FROM TableA WHERE id = 5";
return sessionFactory.getCurrentSession().createQuery(hql).list();

It will return all the rows from TableB which are mapped for id =5. But I want to add one more condition like added_date = XXXX.

Is it possible to add filter in query or by any other way on column added_date ?

Upvotes: 0

Views: 307

Answers (1)

Thierry
Thierry

Reputation: 5440

Yes it is possible from the query :

look at the hql documentation : http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#queryhql

You want something like

String hql = "select a from TableA as a inner join a.tableBList as b WHERE a.id = :id and b.added_date > :after";
Query q = sessionFactory.getCurrentSession().createQuery(hql);
q.setParameter("id", 5);
q.setParameter("after", date);
q.list();

Upvotes: 1

Related Questions