Search code examples
javahibernateclasscastexceptionnamed-query

Hibernate named query ClassCastException


This might be duplicate of this but did not get proper solution over there. I am using named query to fetch some details as below and returning as list of string,

<sql-query name="getContactIds">
    <return-scalar column="id" type="string" />
        <![CDATA[Select c.id as id from CRM.dbo.contact c where is_deleted=0]]>
</sql-query> 

But when calling this query, I am getting java.lang.RuntimeException: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map

SearchTemplate searchTemplate = new SearchTemplate();
searchTemplate.setNamedQuery("getContactIds");
searchTemplate.setNamedQueryResultType(String.class);
salesforceContactIds=contactDao.getSfContactIds(searchTemplate);

Appreciate any help in this regard.


Solution

  • JPQL is query language from Hibernate/JPA. And it works with entities and not with tables. So if you have Contact java entity with field deleted which is mapped to Contact table

    @Entity
    @Table(name = "CONTACT", schema = "name")
    public class Contact {
    
        @Id
        private Integer id;
    
        @Column(name = "is_deleted", nullable = false)
        private boolean deleted;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public boolean isDeleted() {
            return deleted;
        }
    
        public void setDeleted(boolean deleted) {
            this.deleted = deleted;
        }
    

    then select should be something like

    select * from Contact c where c.deleted = 0
    

    And then get id or other necessary fields from Contact.

    If you want to use SQL syntax then you need to use NamedNativeQuery