无法将java.lang.Object强制转换为自定义对象

时间:2017-12-14 22:35:27

标签: java hibernate

我试图通过强制转换Object引用来获取分配给自定义类的hql查询结果。但它抛出异常。但我已经看到开发人员将从查询返回的对象引用转换为自定义类引用而没有任何问题。

我想要的是,

//地址类

package car;

public class Address {

private int addId;    
private String city;
private String country;

    public String getCity() {
        return city;
    }

    public int getAddId() {
        return addId;
    }

    public void setAddId(int addId) {
        this.addId = addId;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }


}

// Hibernate映射

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name = "car.Address" table = "studentAddress">
        <id name = "addId">
            <generator class = "assigned"/>
        </id>
        <property name = "city" column = "city"/>
        <property name = "country" column = "country" />
    </class>

</hibernate-mapping>

//测试类

public class Main {

    public static void main(String[] args) {


            Configuration cfg = new Configuration();
            cfg.configure("retail\\resources\\hibernate.cfg.xml");
            SessionFactory s = cfg.buildSessionFactory();
            Session ss = s.openSession();
            Transaction t = ss.beginTransaction();

            Student stu = new Student();
            stu.setSid(11);
            stu.setName("Thanweer");
            stu.setAge(28);

            Address a = new Address();
            a.setAddId(22);
            a.setCity("Colombo");
            a.setCountry("Sri Lanka");

            Query q = ss.createQuery("select city,country from Address a where a.city = 'Colombo'" );
            Address a2 = (Address)q.uniqueResult();
            System.out.println(a2.getAddId()+" "+a2.getCity()+" "+a2.getCountry());

    }

}

发生异常是:

INFO: HHH000232: Schema update complete
Hibernate: select address0_.city as col_0_0_, address0_.country as col_1_0_ from studentAddress address0_ where address0_.city='Colombo'
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to car.Address
    at test.Main.main(Main.java:36)

1 个答案:

答案 0 :(得分:1)

关注HQL

select city,country from Address a where a.city = 'Colombo'

选择对象数组列表。这就是为什么[Ljava.lang.Object;有关详细信息,请参阅this问题。

在每个数组中,索引0包含String city,索引1包含String country。使用uniqueResult()结果不再是列表,而是简单的对象数组。如果首选Address,则应选择Address,如下所示:

Query q = ss.createQuery("select a from Address a where a.city = 'Colombo'" );
Address a2 = (Address)q.uniqueResult();