Skip to content
Advertisement

Cast exception when trying to get the resultset in hibernate “Cannot cast ‘java.lang.Object[]’ to”

In my application im using Hibernate 3.3 for the data connection. When im trying to get the resultset by a native query, it throws Cannot cast 'java.lang.Object[]' to org.model.Term exception.

Model class :

@Entity
@Table(name = "term")
public class Term {

   @Id
   @GeneratedValue(strategy= GenerationType.AUTO)
   @Column(name = "version")
   private long versionId;

   @Column(name = "name")
   private String name;

   @Column(name = "created_date")
   private Date createdDate;
}

Dao method :

  @Repository
  @Transactional
  public class TermsDao {

  private static final String findLatestQuery = "select * from term WHERE version = (select max(version) from term)";

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional(readOnly = true)
    public Term findLatestTerm() {

    Query query = entityManager.createNativeQuery(findLatestQuery);
    return (Term) query.getSingleResult();
   }

}

persistence config :

<persistence version="1.0"
         xmlns="http://java.sun.com/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
     http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>org.model.Term</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
        <!--<property name="hibernate.hbm2ddl.auto" value="update"/>-->
    </properties>
</persistence-unit>

table structure :

 Field                     Type          Key  Extra          

 version                   bigint(20)    PRI  auto_increment 
 name                      varchar(255)                      
 created_date              datetime                          

When query.getSingleResult(); is evaluated the results are there.

query.getSingleResult().getClass() returns `[Ljava.lang.Object;`

What might be causing this issue?

Advertisement

Answer

EntityManager.createNativeQuery(String sqlString) is meant for UPDATE and DELETE statements:

If the query is not an update or delete query, query execution will result in each row of the SQL result being returned as a result of type Object[] (or a result of type Object if there is only one column in the select list.)

Use createNativeQuery(String sqlString, Class resultClass) instead, i.e:

Query query = entityManager.createNativeQuery(findLatestQuery, Term.class);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement