Kien Dang Ngoc
Kien Dang Ngoc

Reputation: 1079

manage return type hibernate

I'm using native query to get data from database and add them into an object that content float values like:

select tons, delivered_tons from contract where id = 1

and using createSQLQuery() to execute the query

and return an object array like:

Object[] result = (Object[])query.uniqueResult();

and cast them into my object

A a = new A((Float)result[0],(Float)result[1]);

The problem is that I can't know the return type of the query (float or double). So do hibernate has any method to control the return type?

Upvotes: 0

Views: 607

Answers (1)

JB Nizet
JB Nizet

Reputation: 692071

If you used HQL instead os SQL, Hibernate would use the types that you chose to map the columns in your entity:

Assuming you have a Contract entity containing these fields:

@Entity
public class Contract {
    @Column(name = "tons")
    private Float tons;

    @Column(name = "delivered_tons")
    private Float deliveredTons;

    ...
}

You would simply execute the HQL query

select c.tons, c.deliveredTons from Contract c where c.id = :id

and you would be sure to get an array containing two Floats.

That said, for such a simple query, why don't you just use

Contract c = (Contract) session.get(Contract.class, id);

and then get the fields you want from the entity?

Upvotes: 1

Related Questions