Hibernate-select new Object(Entity obj)非主外键关联对象查询[@more@]
1.定义实体类
/**
* Name: net.uni.in1.model.RoleDict.java
* Version: 1.0
* Date: 2011-11-21
* Author: Administrator
*/
package net.uni.in1.model;
/**
* 处理内容: 用于多表非主外键联合查询用的
* @version: 1.0
* @see:net.uni.in1.model.RoleDict.java
* @date:2011-11-21
* @author:孙伟
*/
public class RoleDict {
private Role role = new Role();
private String dictName;
private String code;
private Long dictUniqNo;
/**
*
Title:
*
Description:
* @param role
* @param dictName
* @param code
* @param dictUniqNo
*/
public RoleDict(Object role, String dictName, String code, Long dictUniqNo) {
super();
this.role = (Role)role;
this.dictName = dictName;
this.code = code;
this.dictUniqNo = dictUniqNo;
}
public RoleDict() {
super();
// TODO Auto-generated constructor stub
}
public String getDictName() {
return dictName;
}
public void setDictName(String dictName) {
this.dictName = dictName;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getDictUniqNo() {
return dictUniqNo;
}
public void setDictUniqNo(Long dictUniqNo) {
this.dictUniqNo = dictUniqNo;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
2.hql语句
String sql = "SELECT e as role,t.name as dictName,t.code as code,t.dictUniqNo as dictUniqNo FROM net.uni.in1.model.Role e,net.uni.in1.model.Dict t WHERE e.uniqNo=t.dictUniqNo";
注意:as后面的名称要与实体类里面的成员变量名称类型相同
3.创建query
Query query=this.getSession().createQuery(sql).setResultTransformer(Transformers.aliasToBean(net.uni.in1.model.RoleDict.class));
RoleDict就是你需要new出来的object
最后query.list的结果就是List