Hibernate 原生查询

public void sqlQuery() {
		
		Session session = null ;
		Transaction tx = null;
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			String sql = "select distinct t.*,r.rolename as ronm from t_user t,t_user_role b, t_role r where t.userid = b.userid and b.roleid = r.roleid ";
			Query query = session.createSQLQuery(sql).addEntity("t",TUser.class).addScalar("ronm",Hibernate.STRING);
			//Query query = session.createSQLQuery("select * from t_user").addEntity(TUser.class);
			//Query query =  session.createQuery("from TUser");
			/*List<TUser> list = query.list();
			System.out.println(list.size());
			for (TUser user : list) {
				System.out.println(user.getUsername());
			}*/
			List list = query.list();
			for (Object object : list) {
				Object[] obj = (Object[]) object;
				System.out.println(obj[0]);
				System.out.println(obj[1]);
			}
			 
			
			tx.commit();
			session.flush();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("异常了");
		}finally{
			HibernateSessionFactory.closeSession();
		}
			
			
	}

 

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