日期:2014-05-20 浏览次数:20754 次
Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); String result = (String)session.createQuery("select e.title from Event e where e.id=:pid").setParameter("pid", 1L).uniqueResult(); session.getTransaction().commit();
------解决方案--------------------
BaseHibernateDAO dao = new BaseHibernateDAO(); //查询语句 String strSql = " select * from hrrole h where h.code like ? and h.id <> ?"; //设置查询对象 SQLQuery query = dao.getSession().createSQLQuery(strSql); //设置查询参数 query.setString(0,(String)this.getCode().getText()); //设置查询参数 query.setString(1,this.getTextField1().getText().toString()); //添加到一个类中 query.addEntity(HrRole.class); //结果数据 ArrayList<HrRole> idlist = (ArrayList<HrRole>) query.list(); //判断是否有值 if(idlist.size() != 0){ //错误信息 this.label2.setText("代码已存在"); } Hibernate中使用SQLQuery的更新: public void updateR(String Code,String NewCode){ BaseHibernateDAO dao = new BaseHibernateDAO(); try{ Transaction tx = dao.getSession().beginTransaction(); String sql1 = "update roleandgrant set rolecode = '" + Code + "'" + " where rolecode ='" + NewCode + "'"; String sql2 = "update emprole set rolecode = '" + Code + "'" + " where rolecode ='" + NewCode + "'"; SQLQuery query1 = dao.getSession().createSQLQuery(sql1); SQLQuery query2 = dao.getSession().createSQLQuery(sql2); query1.addEntity(RoleAndGrant.class); query2.addEntity(EmpVsRole.class); query2.executeUpdate(); query1.executeUpdate(); tx.commit(); dao.closeSession(); }catch(Exception ex){ System.out.println(ex); dao.closeSession(); } } Hibernate中使用SQLQuery的删除: public void DeleteR(String Code){ BaseHibernateDAO dao = new BaseHibernateDAO(); try{ Transaction tx = dao.getSession().beginTransaction(); String sql1 = "delete from roleandgrant where rolecode ='" + Code + "'"; String sql2 = "delete from emprole where rolecode ='" + Code + "'"; SQLQuery query1 = dao.getSession().createSQLQuery(sql1); SQLQuery query2 = dao.getSession().createSQLQuery(sql2); query1.addEntity(RoleAndGrant.class); query2.addEntity(EmpVsRole.class); query2.executeUpdate(); query1.executeUpdate(); tx.commit(); dao.closeSession(); }catch(Exception ex){ System.out.println(ex); dao.closeSession(); } }