hibernate left关联查询返回自定义VO

需求:多表关联查询,获取每张表中需要的字段

1、创建UserAccountInfoVo实体类,设置get set 方法,字段都为小写,后面sql即使as成大写,返回结果也是小写,会造成找不到setter方法

public class UserAccountInfoVo implements Serializable {

	private static final long serialVersionUID = 4187685806810273558L;

	private int userid;
	private int orgid;
	private String username;
	private Date loginexpiredate;
	private String email;

	public UserAccountInfoVo() {
	};

	public UserAccountInfoVo(int userid, int orgid, String username, Date loginexpiredate, String email) {
		super();
		this.userid = userid;
		this.orgid = orgid;
		this.username = username;
		this.setLoginexpiredate(loginexpiredate);
		this.email = email;
	}

	public int getUserid() {
		return userid;
	}

	public void setUserid(int userid) {
		this.userid = userid;
	}

	public int getOrgid() {
		return orgid;
	}

	public void setOrgid(int orgid) {
		this.orgid = orgid;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}


	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public Date getLoginexpiredate() {
		return loginexpiredate;
	}

	public void setLoginexpiredate(Date loginexpiredate) {
		this.loginexpiredate = loginexpiredate;
	}

}

2、通过ResultTransformer这个类 AliasToBean,通过sql的查询,会返回数组,然后 hibernate根据数据表的映射,自动帮我们来set对应的字段属性,查询的值与设置的vo对应

String sql = "select u.id as userid,u.organizationid as orgid,u.lastname as username,o.login_expire_date as loginExpireDate,u.email from \""
					+ userTable + "\" u ,\"" + organizationTable
					+ "\" o where u.organizationid = o.id and o.type <> 'Free'";
			Query setResultTransformer = session.createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(UserAccountInfoVo.class));
			List UserAccountInfoList = setResultTransformer.list();

参考:https://blog.csdn.net/woshixuye/article/details/7289286

你可能感兴趣的:(数据库)