休眠:java.lang.ClassCastException:java.lang.Integer 不能转换为 java.lang.Double

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19994365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:08:38  来源:igfitidea点击:

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

javahibernatecastingclasscastexception

提问by Amitab Das

My Staff Entity defined in Java is like this :

我在 Java 中定义的 Staff 实体是这样的:

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?

有没有办法在没有显式转换的情况下做到这一点?我还认为在 Java 中,Integer 到 Double 的转换是隐式的?

采纳答案by Suresh Atta

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

Hibernate 认为它是一个整数,告诉它是双精度的。

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

回答by Scary Wombat

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

限制.eq 接受一个对象,因此不可能进行隐式转换。