gpt4 book ai didi

java - Hibernate SQL 查询结果映射/转换为对象/类/Bean

转载 作者:搜寻专家 更新时间:2023-10-30 20:59:41 24 4
gpt4 key购买 nike

1 2: select (table.*)/(all column) 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: 选择某列(不是全部),报错

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

我想让“3”正常工作,让结果可以映射到Student.class。
比如:Student[id=?, name=?, sex=?, (其他字段为空/默认)]
我不知道这个错误,请帮助我!

最佳答案

您可以进一步添加.setResultTransformer(Transformers.aliasToBean(YOUR_DTO.class));并自动将其映射到您的自定义 dto 对象,另请参阅 Returning non-managed entities .

例如:

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;
}

关于java - Hibernate SQL 查询结果映射/转换为对象/类/Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17355980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com