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:

  1. The number of Bar results returned are the same (and correct)

  2. but in the criterion cases a Bar with a List<Foo> returns roughly 10x more Foo objects than the corresponding SQL query does. All the extra Foo 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;
}
Was it helpful?

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top