Hibernate中查询数据转成VO对象及注意问题

大家都可能会遇到,在用json传输数据时,很多字段是来自不同的表数据,需要我们进行封装数据。

hibernate提供这么一个方法用来直接封装查询属性:

query.setResultTransformer(Transformers.aliasToBean(VO.class));

Example:

session.createQuery("select u.name as name , u.age as age from User as u").setResultTransformer(Transformers.aliasToBean(UserVo.class)).list();

其中红色代码为自定义vo中的属性,可直接用List<UserVo>接收。

这里需要注意:当User中有name字段或age字段为空(null)的情况,此条数据不会封装进List<UserVo>集合中。

原文地址:https://www.cnblogs.com/tobey/p/4761334.html