I was trying to fetch hql query result assigned to custom class by casting the Object reference. but it throws for exception. But i have seen developers casting object reference returned from query to custom class reference without any issues.
What i wanted is,
//Address class
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 mapping
<?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>
//Test class
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());
}
}
Exception Occurs is :
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)