hibernate sql 自定义字段 返回自定义bean对象
阅读(1746)
2018-01-17
hibernate用原生SQL查询如何返回自定义对象而非实体对象呢?使用SQLQuery对象的addScalar()和setResultTransformer()可以实现。
首先定义实体:
package com.weizhixi.entity; import javax.persistence.*; @Entity public class User { private int id; private String name; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
再自定义vo或者其他bean类
package com.weizhixi.vo; public class UserVo { private int id; private String name; private String fname;//注意,这个字段实体类是没有的 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } }
接下来演示查询:select u.id, u.name, u.name as fname from user u 原生sql,自定义了fname字段,fname不是实体属性和数据库字段。查询后返回UserVo值对象。
Query query = session.createSQLQuery("select u.id,u.name,u.name as fname from user u") .addScalar("id", Hibernate.INTEGER) .addScalar("name", Hibernate.STRING) .addScalar("fname", Hibernate.STRING) .setResultTransformer(Transformers.aliasToBean(UserVo.class)); List<UserVo> users = query.list(); for(UserVo user : users){ System.out.println(user.getId() + "\t-\t"+user.getName() + "\t-\t" + user.getFname()); }
控制台:
Hibernate: select u.id,u.name,u.name as fname from user u 1 - hello - hello
原创文章,转载请注明出处:https://www.weizhixi.com/article/62.html