hibernate实现查询,修改,插入,删除操作

xiaoxiao2021-02-28  28

1.首先要先引入hibernate的jar包和相应数据库的驱动

2.配置hibernate.cfg.xml和相关bean的hbm.xml文件。

3.开启Configuration,SessionFactory 。

Configuration cfg = new Configuration().configure(); SessionFactory sf = cfg.buildSessionFactory();

4.打开session

Session sess1 = sf.openSession();

5.开启事物

Transaction transaction = sess1.beginTransaction();

6.开始增删改查

插入操作:

work.setCode(request.getParameter("code")); work.setName(request.getParameter("name")); work.setDetail(request.getParameter("detail")); work.setCount(Integer.parseInt(request.getParameter("count"))); sess1.save(work);transaction.commit();

修改操作:

String hql = "from Work where code='"+code+"'"; Query<Work> query= (sess4.createQuery(hql));  Work work = query.list().get(0); work.setName(name); work.setDetail(detail); work.setCount(count); transaction.commit();

查询操作:

String hql = "from Work where name='"+name+"'"; Query<Work> query= sess4.createQuery(hql); Work a = query.uniqueResult(); Work work = null; if (a != null) { work = query.list().get(0); }else{ work = null; } transaction.commit();

删除操作:

String hql = "delete from Work where code='"+code+"'"; int query = sess3.createQuery(hql).executeUpdate();  transaction.commit();

 

注:每次进行操作之后必须commit来将缓冲区内容清空并提交事务,不提交会造成锁的不释放。

flush()和clear()同样也是清空缓冲区提交事务的方法,但不建议使用。

事务执行完毕后要close

转载请注明原文地址: https://www.6miu.com/read-2000010.html

最新回复(0)