Update:. I tested the approach suggested below, and I couldn't get it to work for this particular scenario, Hibernate expects you to select columns for all attributes, while we definitely do not want an identifier. However, using ResultTransformer really worked:
You can apply ResultTransformer to native SQL queries, allowing it to return ResultTransformer objects.
sess.createSQLQuery("SELECT NAME, BIRTHDATE FROM CATS") .setResultTransformer(Transformers.aliasToBean(CatDTO.class))
The specified request:
- SQL query string
- result transformer
The above query will return the CatDTO list that was created and entered the NAME and BIRTHNAME values ββin the corresponding properties or fields.
The documentation mentions returned unmanaged objects, but it also works with the entity (there is no reason why it will not work), and I could persist transition object successfully.
see also
I leave the original answer for the sake of clarity.
Perhaps the following will help:
The above questions concerned returning scalar values, mostly returning "raw" values ββfrom a ResultSet. The following shows how to get object objects from a native sql query through addEntity() .
sess.createSQLQuery("SELECT * FROM CATS").addEntity(Cat.class); sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE FROM CATS").addEntity(Cat.class);
The specified request:
- SQL query string
- the object returned by the request
Assuming Cat is displayed as a class with column identifiers, NAME and BIRTHDATE, the above queries will return a list in which each item is a Cat Object.
If an object is mapped to a many-to-one other object, it is also required to return this when executing its own query, otherwise the database "column not found" error. Additional columns will be automatically returned when using * notation, but we prefer to be explicit, as in the following many-to-one Dog example:
sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE, DOG_ID FROM CATS").addEntity(Cat.class);
This will allow cat.getDog() to function properly.
But I donβt think you should set the ID if you want to save it and you want Hibernate to perform the insertion. Strike>