Hibernate SQLQuery 注册VO

   有时候HQL并不能满足我们的查询需求,利用SQLQuery来执行SQL语言,注册一个POJO对象只需要addEntity()方法就可以了,下面看看怎么注册VO对象。测试代码
String sql = "select userid,username,pword,position from USER_USERINFO where userid=1";
		Configuration conf = new Configuration().configure();
		SessionFactory sessionFactory = conf.buildSessionFactory();
		Session session = sessionFactory.openSession();
		SQLQuery sqlQuery = session.createSQLQuery(sql);
		//注册VO的类型。
		sqlQuery.addScalar("userid", Hibernate.LONG);
		sqlQuery.addScalar("username", Hibernate.STRING);
		sqlQuery.addScalar("pword", Hibernate.STRING);
		sqlQuery.addScalar("position", Hibernate.INTEGER);
		//注册PO
		//UserPo user = (UserPo)sqlQuery.addEntity(UserPo.class).uniqueResult();
		//注册VO
		UserVo userVo = (UserVo)sqlQuery.setResultTransformer(Transformers.aliasToBean(UserVo.class)).uniqueResult();
		System.out.println(userVo.getUserid()+"  "+userVo.getUsername()+"  "+userVo.getPword()+"  "+userVo.getPosition());


最好用addScalar()将类型注册一下,有时候会出现类型转换异常。

你可能感兴趣的:(sql,Hibernate)