I am trying to use Hibernate with SQL Server .
I want to select the rows from SQL Server and cast them to Places objects.
I will write the codes I tried and exceptions I got.
List places = session.createQuery("FROM PLACES").list();
for (Iterator iterator = places.iterator(); iterator.hasNext();){
Place place = (Place) iterator.next();
}
Exception:
SEVERE: Incorrect syntax near the keyword 'from'.
This code generates
select from
and since SQL Server needs something between select and from this query fails
So I tried to change the code to
List places = session.createSQLQuery("SELECT ID,NAME FROM [PLACES].[dbo].[PLACES]").list();
for (Iterator iterator = places.iterator(); iterator.hasNext();){
Place place = (Place) iterator.next();
}
Exception:
Exception in thread "main" java.lang.ClassCastException
Since this query returns an Object[] I can not cast it.
How can I get rows and cast them to Places objects
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="com.places.general.Place" table="PLACES" schema="dbo">
<id name="id" type="int">
<column name="ID"/>
<generator class="identity"/>
</id>
<property name="name" type="string">
<column length="100" name="NAME" not-null="true"/>
</property>
</class>
</hibernate-mapping>
In the HQL statement you have to use the Java class name, not the table name:
or
And your second try returns a list of arrays of Object, each array first element is id, second is name, which have to be casted to Integer and String separately.