Hibernate数据库增删改查代码
//hql语句查询 public ArrayList findClassByHql(String hql){ ArrayList list= new ArrayList(); Session session=null; Transaction tc=null; try{ session=HibernateSessionFactory.getSession(); tc=session.beginTransaction(); Query qy=session.createQuery(hql); if(qy!=null){ list=(ArrayList)qy.list(); } tc.commit(); }catch(Exception e){ e.printStackTrace(); } finally { if(session!=null) { session.close(); } } return list; } //通过ID得到类, public Account findAccountByID(String userName){ Account account=new Account(); Session session=null; Transaction tc=null; try{ session=HibernateSessionFactory.getSession(); tc=session.beginTransaction(); account =(com.my.jkp.hibernate.Account)session.load(com.my.jkp.hibernate.Account.class,userName ); }catch(Exception e){ e.printStackTrace(); if(tc!=null){ tc.rollback(); } } finally{ if(session!=null){ session.close(); } } return account; } //查询所有用户信息 public ArrayList findAllAccount(){ ArrayList list=new ArrayList(); String hql="from Account"; list=this.findClassByHql(hql); return list; } //增加用户 public boolean saveAccount(Account account){ boolean tag=false; Session session=null; Transaction tc=null; try{ session=HibernateSessionFactory.getSession(); tc=session.beginTransaction(); session.save(account); tc.commit(); }catch(Exception e){ e.printStackTrace(); } finally { if(session!=null) { session.close(); } } return tag; } //修改用户 public boolean updateAccount(Account account){ boolean tag=false; Session session=null; Transaction tc=null; try{ session=HibernateSessionFactory.getSession(); tc=session.beginTransaction(); session.update(account); tc.commit(); }catch(Exception e){ e.printStackTrace(); } finally { if(session!=null) { session.close(); } } return tag; } //删除用户 public boolean deleteAccount(String userName){ boolean tag=false; Session session=null; Transaction tc=null; Account Account=new Account(); try{ session=HibernateSessionFactory.getSession(); tc=session.beginTransaction(); Account =(com.my.jkp.hibernate.Account)session.load(com.my.jkp.hibernate.Account.class,userName ); session.delete(Account); tc.commit(); }catch(Exception e){ e.printStackTrace(); } finally { if(session!=null) { session.close(); } } return tag; }
注意:使用HIbernate对数据库进行操作,必须使用事务进行提交。
相关推荐
solarspot 2020-07-28
houmenghu 2020-11-17
我心似明月 2020-11-09
oraclemch 2020-11-06
ltd00 2020-09-12
康慧欣 2020-09-10
waveclouds 2020-09-04
蓝色深海 2020-09-15
jincheng 2020-09-01
思君夜未眠 2020-08-25
取个好名字真难 2020-08-06
歆萌 2020-08-03
阳光之吻 2020-08-03
婷婷小屋 2020-07-28
MLXY 2020-07-26
dxbjfu0 2020-07-26
songbinxu 2020-07-19
83520298 2020-07-06