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

Tags: , ,

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 :

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

   @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 :

  public class TermsDao {

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

    private EntityManager entityManager;

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

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


persistence config :

<persistence version="1.0"
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
        <!--<property name="" value="update"/>-->

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?


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);

Source: stackoverflow