Hibernate Session操作
1.增加
@Test public void add(){ Configuration cfg=new Configuration().configure(); SessionFactory factory=cfg.buildSessionFactory(); Session session=factory.openSession(); Emps emp=new Emps("cat","女",15,30,2000); session.save(emp); session.close(); factory.close(); }
2.查询
@Test public void query1(){ Configuration cfg=new Configuration().configure(); SessionFactory factory=cfg.buildSessionFactory(); Session session=factory.openSession(); Emps emp=(Emps) session.get(Emps.class, 1005); System.out.println(emp.toString()); session.close(); factory.close(); }
延迟加载:
get方法:调用立刻发出sql查询
load方法:调用不发出sql,当我们需要使用该对象时才查询
Query:
当查询结果只有一个的时候可以使用uniqueResult()方法。
Emps emp=(Emps) query.uniqueResult();
分页:
Query query = session.createQuery("from Emps"); //分页 //从第几个开始取结果 query.setFirstResult(0); //每页最多有几个结果 query.setMaxResults(3); List<Emps> list = query.list();
3.修改表-需要创建事务
@Test public void update(){ Configuration cfg=new Configuration().configure(); SessionFactory factory=cfg.buildSessionFactory(); Session session=factory.openSession(); Transaction ts=session.beginTransaction(); Emps emp=(Emps) session.get(Emps.class, 1005); emp.setAge(30); session.update(emp); ts.commit(); System.out.println(emp.toString()); session.close(); factory.close(); }
4.删除
@Test public void delete(){ Configuration cfg=new Configuration().configure(); SessionFactory factory=cfg.buildSessionFactory(); Session session=factory.openSession(); Transaction ts=session.beginTransaction(); //根据ID删除; Emps emp=new Emps(); emp.setId(1019); session.delete(emp); ts.commit(); session.close(); factory.close(); }
5.查询所有对象(HQL)
HQL:Hibernate Query Language
@Test public void query2(){ Configuration cfg=new Configuration().configure(); SessionFactory factory=cfg.buildSessionFactory(); Session session=factory.openSession(); Query query = session.createQuery("from Emps");//Emps是一个类名 List<Emps> list = query.list(); for(Emps e:list){ System.out.println(e); } session.close(); factory.close(); }
6. Criteria查询
@Test public void query3(){ Configuration cfg=new Configuration().configure(); SessionFactory factory=cfg.buildSessionFactory(); Session session=factory.openSession(); //Criteria 查询:Hibernate面向对象的查询(无语句) Criteria criteria=session.createCriteria(Emps.class); List<Emps> list = criteria.list(); for(Emps e:list){ System.out.println(e); } session.close(); factory.close(); }
7.Sql查询
@Test public void query4(){ Configuration cfg=new Configuration().configure(); SessionFactory factory=cfg.buildSessionFactory(); Session session=factory.openSession(); SQLQuery createSQLQuery = session.createSQLQuery("select * from emps"); createSQLQuery.addEntity(Emps.class); List<Emps> list = createSQLQuery.list(); for(Emps e:list){ System.out.println(e); } session.close(); factory.close(); }