Pete Long
Pete Long

Reputation: 107

Criteria Query using Postgres

Using :- Postgres : PostgreSQL 10.0 Hibernate : 4.0.1

I have the following example table created in Postgres

CREATE TABLE Automobile
(id                          SERIAL               
,name                        VARCHAR(20)        
,year                        INTEGER        
);

I have created a domain Automobile class.

I have the following hibernate criteria query to return all the names for a particular year.

    final Criteria criteria = session.createCriteria (Automobile.class);

    criteria.add (Restrictions.eq ("year", 1 ));

    List<Automobile> list = criteria.list();

However, the list() is generating the following exception.

    java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

So I changed query to pass in a String value for the "year" :-

    criteria.add (Restrictions.eq ("year", new String("1")));

    List<Automobile> list = criteria.list();

However, the list() is generating a different exception.

    org.hibernate.exception.SQLGrammarException: ERROR: operator does not exist: integer = character varying
    Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
    Position: 1145

Any thoughts on what maybe the cause and solution that would return me list of matches please ?

Thank you Pete.

Upvotes: 0

Views: 1138

Answers (1)

mentallurg
mentallurg

Reputation: 5207

In the Hibernate mapping you have

<property name="year" type="java.lang.String" >

You didn't show you Java code. I suppose year is also String there.

But in the database year is an integer.

Solution: Change your mapping as follows: Also change your Java class and define year as Integer.

Upvotes: 1

Related Questions