操作Hibernate类大致有增加,删除,修改及检查四种,简称为增删改查。以下为实现代码:
- /*
- *具体操作hibernate的类
- *增加,删除,修改,按ID查询,模糊查询,查询全部
- **/
- public class PersonOperate {
- //在hibernate中所有操作都是由Session完成
- public Session session = null;
- //在构造方法中实例化Session对象
- public PersonOperate(){
- //找出hibernate的配置
- Configuration config = new Configuration().configure();
- //从配置中取出SessionFactory
- SessionFactory sf = config.buildSessionFactory();
- //从SessionFactory中取出Session
- this.session = sf.openSession();
- }
- //操作Hibernate类的所有操作都是通过Session完成的
- //增加数据库中数据
- public void insert(Person person){
- //开始事务
- Transaction tran = session.beginTransaction();
- //执行语句
- session.save(person);
- //提交事务
- tran.commit();
- session.close();
- }
- //操作Hibernate类更改数据库中的数据
- public void update(Person person){
- //开始事务
- Transaction tran = session.beginTransaction();
- //执行语句
- session.update(person);
- //提交事务
- tran.commit();
- }
- /*操作Hibernate类:按ID查询
- *我们插入,修改都是对对象进行操作
- *那么我们查询的时候也应该是返回一个对象
- **/
- public Person queryById(String id){
- System.out.println(id);
- Person person = null;
- //hibernate查询语句
- String hql = "FROM Person as p WHERE p.id = ?";
- Query q = session.createQuery(hql);
- q.setString(0, id);
- List list = q.list();
- Iterator iteator = list.iterator();
- if(iteator.hasNext()){
- person = (Person)iteator.next();
- }
- return person;
- }
- /*操作Hibernate类:删除数据库中数据
- *hiberante2,hibernate3中通用的删除方法
- *缺点:删除数据之前要先查询一次数据,找出删除的数据对象
- *性能低下
- **/
- public void delete(Person person){
- //开始事务
- Transaction tran = session.beginTransaction();
- //执行语句
- session.delete(person);
- //提交事务
- tran.commit();
- }
- //hibernate3的用法
- public void delete(String id){
- //开始事务
- Transaction tran = session.beginTransaction();
- String hql = "DELETE Person WHERE id = ?";
- Query q = session.createQuery(hql);
- q.setString(0, id);
- //执行更新语句
- q.executeUpdate();
- //提交事务
- tran.commit();
- }
- //操作Hibernate类:查询全部数据
- public List queryAll(){
- List list = null;
- String hql = "FROM Person as p ";
- Query q = session.createQuery(hql);
- list = q.list();
- return list;
- }
- //操作Hibernate类:模糊查询
- public List queryByLike(String colnum,String value){
- List list = null;
- String hql = "FROM Person as p WHERE p."+ colnum +" like ?";
- Query q = session.createQuery(hql);
- q.setString(0, "%"+ value +"%");
- list = q.list();
【编辑推荐】