package com.finder.hibernate.dao; import java.util.Iterator; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import com.finder.hibernate.model.Student; import com.finder.hibernate.util.HibernateUtil; public class StudentDao { /** * insert */ public void addStudent( Student student ){ Session session = HibernateUtil.getSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.save(student); tx.commit(); } catch (HibernateException he) { tx.rollback(); he.printStackTrace(); }finally{ session.close(); } } /** * select */ public Student getStudent( int id ){ Session session = HibernateUtil.getSession(); Transaction tx = null; Student student = null; try { tx = session.beginTransaction(); student = (Student) session.get(Student.class, new Integer(id)); tx.commit(); } catch (HibernateException he) { tx.rollback(); he.printStackTrace(); } return student; } /** * update */ public void updateStudent( String oldName, String newName ){ Session session = HibernateUtil.getSession(); Transaction tx = null; try { tx = session.beginTransaction(); Query query = session.createQuery("from Student s where s.name = ?"); query.setParameter(0, oldName); Iterator<Student> it = query.list().iterator(); while( it.hasNext() ){ Student s = it.next(); s.setName(newName); session.update(s); } tx.commit(); session.close(); } catch (HibernateException he) { tx.rollback(); he.printStackTrace(); } } /** * delete */ public void deleteStudent(String str){ Session session=HibernateUtil.getSession(); Transaction tx=null; try { tx=session.beginTransaction(); /* 1.Criteria查询; */ Criteria criter=session.createCriteria(Student.class).add(Restrictions.like("name","%"+str+"%")); Iterator<Student> it=criter.list().iterator(); /* 2.Query查询 Query q=session.createQuery("from Student as s where s.name like ?"); q.setParameter(0, "%"+str+"%"); Iterator<Student> it=q.list().iterator(); */ /* 3.Native sql查询 表名和表中的列名而不是实体类的类名和属性名了 SQLQuery sqlq=session.createSQLQuery("SELECT * FROM s WHERE sname like ?").addEntity(Student.class); sqlq.setParameter(0, "%"+str+"%"); Iterator<Student> it=sqlq.list().iterator(); */ while(it.hasNext()){ session.delete(it.next()); } tx.commit(); } catch (HibernateException he) { tx.rollback(); he.printStackTrace(); } finally { session.close(); } } }
最近下载更多
Pilgrim LV1
2021年9月18日
林志勇 LV10
2020年4月28日
krislijixiang LV8
2020年3月28日
元芳你怎么看 LV15
2020年3月5日
17704627276 LV17
2019年12月30日
si599163126 LV5
2019年11月10日
unique11 LV3
2019年8月16日
moonio LV1
2019年7月3日
orioncny LV6
2019年2月12日
1742204618ok LV2
2019年1月22日
最近浏览更多
彩色天空 LV5
2023年4月2日
kk992127170 LV6
2023年2月26日
liweb 010928 LV1
2022年10月31日
cqbscxh LV11
2022年9月19日
lvchengliang LV4
2022年6月16日
xz2000525 LV2
2022年6月8日
放开那女孩 LV15
2022年3月17日
过过成功尺寸 LV7
2021年12月6日
c123456x LV2
2021年12月4日
Pilgrim LV1
2021年9月18日