Hibernate Date Criteria fails but HQL works
-
14-03-2021 - |
Question
Hibernate seems to incorrectly handle date ranges using the Criterion API in Oracle. The SQL Query itself seems correct (copied it from Hibernate and executed it manually). So,
given
Clazz<Bar> clazz;
Date start, end;
this fails
List<Bar> bars = sessionFactory.getCurrentSession()
.createCriteria(clazz)
.add(Restrictions.between("timestamp", start, end))
.list();
and this
List<Bar> bars = sessionFactory.getCurrentSession()
.createCriteria(clazz)
.add(Restrictions.ge("timestamp", start))
.add(Restrictions.le("timestamp", end))
.list();
but this works
List<Bar> bars = sessionFactory.getCurrentSession()
.createQuery("from Bar b where b.timestamp > ? and b.timestamp < ?")
.setDate(0, start)
.setDate(1, end)
.list();
The fail observation is:
The number of
Bar
results returned are the same (and correct)but in the criterion cases a
Bar
with aList<Foo>
returns roughly 10x moreFoo
objects than the corresponding SQL query does. All the extraFoo
objects are identical copies.
EDIT
@Entity
public class Bar {
@Id
private String id;
@Temporal(TemporalType.TIMESTAMP)
private Date timestamp;
@ManyToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
@JoinTable(
name = "bar_foo",
joinColumns = { @JoinColumn(name = "barid") },
inverseJoinColumns = { @JoinColumn(name = "fooid") }
)
private List<Foo> params;
}
@Entity
public class Foo {
@Id private String id;
}
Solution
I can't remember or look up the rationale behind this right now but what you are seeing might be expected behavior. Try this:
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
OTHER TIPS
Try to rewrite query
List<Bar> bars = sessionFactory.getCurrentSession()
.createCriteria(Bar.class)
.add(Restrictions.ge("timestamp", start))
.add(Restrictions.le("timestamp", end))
.list();
It's the same like you did, but I've never seen examples which variable of class type like you use them.
You should check this link also HQL(hibernate) timestamp range match also this Restrictions Between for Date in Hibernate Criteria
Edit 2: Check the examples in here : http://www.javalobby.org/articles/hibernatequery102/