3

My Staff Entity defined in Java is like this :

final public class Staff {
    private int staffId;
    private String firstName = null;
    private String lastName = null;
    private String Email = null;
    private double salary;
    //and the setters and getters
}

My Query code :

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Staff staff = null;
try {
    Criteria criteria = session.createCriteria(dto.Staff.class);
    criteria.add(Restrictions.eq("salary", 1000000));
    staff = (Staff) criteria.uniqueResult();
} catch(Exception e) {
    System.out.println("Error : " + e);
} finally {
    session.close();
}

But when I run this I get an error which says :

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double

If I explicitly cast the number to a double it works :

criteria.add(Restrictions.eq("salary", (double) 1000000));

Is there any way to do this without the explicit casting? Also I thought that in Java, Integer to Double conversion was Implicit?

2 Answers 2

4

Hibernate considering it as a integer, tell that it's double.

    criteria.add(Restrictions.eq("salary",   1000000d));
3
  • But I haven't used Wrapper classes anywhere Commented Nov 15, 2013 at 5:50
  • Is there any way I could add the 'd' to the number dynamically? Because I am trying to write a function which is supposed to set any type of restriction. In fact it could be an integer or a string. Is there any way to do it? Commented Nov 15, 2013 at 5:58
  • Yes. You could write new Double(xxx.toString()) - this will do the right thing whether xxx is a Double, an Integer, a String or basically anything that can reasonably be converted to a Double. Commented Nov 15, 2013 at 7:26
0

The restriction.eq takes an object, so no implicit casting is possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.