Java – hibernate SQL query result mapping / conversion to object / class / bean
•
Java
1 2: Select (table. * *) / (all columns) ok
String sql = "select t_student.* from t_student"; //String sql = "select t_student.id,t_student.name,... from t_student"; //select all column sqlQuery query = session.createsqlQuery(sql); query.addEntity(Student.class);//or query.addEntity("alias",Student.class); //query.list();[Student@...,Student@...,Student@...] query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); //or other transformer query.list(); //[{Student(or alias)=Student@...},{Student=Student@...}]
3: Selecting some columns (not all) is an error
String sql = "select t_student.id,t_student.name.t_student.sex from t_student"; sqlQuery query = session.createsqlQuery(sql); query.addEntity(Student.class); query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); query.list(); //Exception:invalid column/no column
I want "3" to work properly and map the results to student class. Like: student [id =? Name =? Sex =? (other fields are empty / default)] I don't know this error, please help me!
Solution
You can add further
For example:
public List<MessageExtDto> getMessagesForProfile2(Long userProfileId) { Query query = getSession().createsqlQuery(" " + " select a.*,b.* " + " from messageVO AS a " + " INNER JOIN ( SELECT max(id) AS id,count(*) AS count FROM messageVO GROUP BY messageConversation_id) as b ON a.id = b.id " + " where a.id > 0 " + " ") .addScalar("id",new LongType()) .addScalar("message",new StringType()) ......... your mappings .setResultTransformer(Transformers.aliasToBean(MessageExtDto.class)); List<MessageExtDto> list = query.list(); return list; }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码