I have a query in native sql , something like :
SQLQuery query = session.createSQLQuery("select emp_id, emp_name, emp_salary from Employee");
the query result can be used to set the employee object . On the similar lines , i have the same query appended with addscalar(entity_colname).
query = session.createSQLQuery("select emp_id, emp_name, emp_salary from Employee")
.addScalar("emp_id", new LongType())
.addScalar("emp_name", new StringType())
.addScalar("emp_salary", new DoubleType());
here also we have to obtain the result in the similar way , then what is the advantage of using addscalar?
Regards Jay
When you don't need addScalar
In your example, you don't really need to use
addScalar
.If you map the response to a DTO, like the following
EmployeeDTO
:Then, the following SQL query could fetch the
EmployeeDTO
just fine:Notice that we used column aliases so that Hibernate can match the DTO property we want to set.
When you need addScalar
Assuming you have a
Book
entity that has a JSONproperties
attribute:Now, when executing a native SQL query that fetched the JSON
properties
column:Hibernate throws the following exception:
This is because Hibernate does not know how to transform the
jsonb
column to aJsonNode
Java object since it lacks a Hibernate-native JSONType
.But if we call
addScalar
and provide the HibernateType
:Then the query will run just fine!