HQL中的原生SQL查询

原生SQL-内连接查询

public void sqlJoin(){
		session=HibernateUtil.getSession();
		sql="select {e.*},{d.*} from EMP e inner join DEPT d on e.DEPTNO=d.DEPTNO";
//给查询结果添加实体类,添加连接表的类属性
		Query query =session.createSQLQuery(sql).addEntity("e", Emp.class).addJoin("d", "e.dept");
		List objList=query.list();
		for(Object[] obj:objList){
			System.out.println(obj[0]+" "+obj[1]);
		}
		HibernateUtil.closeSession();
	}

//原生SQL查询-用List接收查询结果
@org.junit.Test

	public void sqlQuery2(){
			session=HibernateUtil.getSession();
			sql="select * from EMP";
			Query query =session.createSQLQuery(sql);
			List objList=query.list();
			for(Object[] obj:objList){
				System.out.println(obj[0]+" "+obj[1]+" "+obj[2]+" "+obj[3]+" "+obj[4]+" "+obj[5]+" "+obj[6]+" "+obj[7]);
			}
			HibernateUtil.closeSession();
		}

//原生SQL查询-在Query中addEntity(Emp.class),这样就可以List接收查询结果
@org.junit.Test

public void sqlQuery(){
		session=HibernateUtil.getSession();
		sql="select * from EMP";
		Query query =session.createSQLQuery(sql).addEntity(Emp.class);
		List elist=query.list();
		for(Emp e:elist){
			System.out.println(e.getEname());
		}
		HibernateUtil.closeSession();
	}	

// 批量处理:JDBC

public void jdbcBatch() {
		session = HibernateUtil.getSession();
		tx = session.beginTransaction();
		Work work = new Work() {
			// 匿名内部类、Work实现类
			@Override
			public void execute(Connection conn) throws SQLException {
				sql = "update Emp set sal=sal+2";
				PreparedStatement pst = conn.prepareStatement(sql);
				pst.executeUpdate();
			}
		};
		session.doWork(work);
		tx.commit();
		HibernateUtil.closeSession();
	}

HQL中的原生SQL查询_第1张图片

你可能感兴趣的:(Hibernate)