hibernate开发步骤

来源:互联网 发布:阿里云cdn如何配置 编辑:程序博客网 时间:2024/05/30 23:01

1、下载hibernate,下载地址
http://hibernate.org/orm/downloads/
解压,将hibernate-release-4.2.4.Final\lib\required目录下的jar包全部导入到项目中
这里写图片描述
2、将配置文件放到SRC目录下,配置hibernate.cfg.xml文件
这里写图片描述
在这个文件中定义了数据库进行连接所需要的信息,包括JDBC驱动、用户名、密码、数据库方言等,configuration类借助dom4j的XML解析器解析设置环境,然后使用这些环境属性来生成 SessionFactory。这样这
个sessionFactory生成的session就能成功获得数据库的连接。

3、写实体的pojo
这里写图片描述

实体类Students
这里写图片描述

4、为实体类写映射文件Students.hbm.xml,并在hibernate.cfg.xml中添加映射的实体
这里写图片描述

这里写图片描述

5、实现类的增、删、改、查操作
这里写图片描述

package services;import java.util.List;import entity.Students;//学生的业务逻辑接口public interface StudentsDAO  {    //查询所有学生资料    public List<Students>queryAllStudents();    //根据学生编号查询学生资料    public Students queryStudentsBySid(String sid);    //添加学生资料    public boolean addStudents(Students s);    //修改学生资料    public boolean updateStudents(Students s);    //删除学生资料    public boolean deleteStudents(String s);}
package service.impl;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import db.MyHibernateSessionFactory;import entity.Students;import services.StudentsDAO;---------//学生业务逻辑接口的实现类public  class StudentsDAOImpl  implements StudentsDAO{    @Override    public List<Students> queryAllStudents() {        // TODO Auto-generated method stub                      Transaction tx=null;            List<Students> list=null;            String hql="";            try{                Session session=MyHibernateSessionFactory.getSessionFactory().getCurrentSession();                tx=session.beginTransaction();                hql="from Students";                Query query=session.createQuery(hql);                 list=query.list();                 tx.commit();                 return list;            }catch(Exception ex){                ex.printStackTrace();                tx.commit();                return list;            }            finally{                if(tx!=null){                    tx=null;                }            }    }               @Override    public Students queryStudentsBySid(String sid) {        // TODO Auto-generated method stub        Transaction tx=null;        Students s=null;                try{            Session session=MyHibernateSessionFactory.getSessionFactory().getCurrentSession();            tx=session.beginTransaction();              s=(Students)session.get(Students.class,sid);             return s;        }catch(Exception ex){            ex.printStackTrace();            tx.commit();            return s;        }        finally{            if(tx!=null){                tx=null;            }        }    }     //生成学生的学号      public String getNewSid(){          Transaction tx=null;          String hql="";          String sid=null;          try{              Session session=MyHibernateSessionFactory.getSessionFactory().getCurrentSession();              tx=session.beginTransaction();              //获得当前学生的最大编号              hql="select max(sid) from Students";              Query query=session.createQuery(hql);              sid=(String)query.uniqueResult();              if(sid==null||"".equals(sid)){                  //给一个默认的最大编号                  sid="001";              }else{                  //String temp=sid.substring(1);//取后七位                  String temp="";                  int i=Integer.parseInt(sid);//转为数字                  i++;                  //再还原为字符串                  temp=String.valueOf(i);                  int len=temp.length();                  //凑够三位                  for(int j=0;j<3-len;j++){                      temp="0"+temp;                  }                  //sid="s"+temp;                  sid=temp;              }              tx.commit();              return sid;          }catch(Exception ex){              ex.printStackTrace();              tx.rollback();              return null;          }finally{              if(tx!=null){                  tx=null;              }          }      }      @Override    public boolean addStudents(Students s) {        // TODO Auto-generated method stub          s.setSid(getNewSid());              Transaction tx=null;              try{                  Session session=MyHibernateSessionFactory.getSessionFactory().getCurrentSession();                  tx=session.beginTransaction();                  session.save(s);                  tx.commit();//事务提交                  return true;              }catch(Exception ex){                  ex.printStackTrace();                  tx.rollback();//事务回滚                  return false;              }finally{                  if(tx!=null){                      tx=null;                  }              }      }    @Override    public boolean updateStudents(Students students) {        Transaction tx=null;        try {            Session session=MyHibernateSessionFactory.getSessionFactory().getCurrentSession();            tx=session.beginTransaction();            //Students students=(Students)session.get(Students.class,sid);            session.update(students);            tx.commit();            return true;        }catch(Exception e)        {            e.printStackTrace();            tx.commit();            return false;        }        finally {            if(tx!=null)            {                tx=null;            }        }    }    @Override    public boolean deleteStudents(String id) {        // TODO Auto-generated method stub         Transaction tx=null;              //String hql="";              try{                  Session session=MyHibernateSessionFactory.getSessionFactory().getCurrentSession();                  tx=session.beginTransaction();                  Students s=(Students)session.get(Students.class, id);                  session.delete(s);                  tx.commit();                  return true;              }catch(Exception ex){                  ex.printStackTrace();                  tx.rollback();                  return false;              }finally{                  if(tx!=null){                      tx=null;                  }              }      }}

6、创建测试类

package entity;import org.junit.Test;import java.util.Date;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;import org.hibernate.tool.hbm2ddl.SchemaExport;import org.junit.Test;    public class TestStudents{        public void TestSchemaExport(){        //创建配置对象            Configuration config=new Configuration().configure();        //创建服务对象            ServiceRegistry serviceRegistry= new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();        //创建session Factory            SessionFactory sessionFactory=config.buildSessionFactory(serviceRegistry);        //创建session对象//          Session session =sessionFactory.openSession();        //shemaExport要重构Hibernate-core使用hibernate4以下的版本,5的不行            SchemaExport export=new SchemaExport(config);            export.create(true,true);        }    //添加测试数据    @Test    public void testSaveStudents(){        //创建配置对象        Configuration config=new Configuration().configure();    //创建服务对象        ServiceRegistry serviceRegistry= new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();    //创建session Factory        SessionFactory sessionFactory=config.buildSessionFactory(serviceRegistry);        Session session=sessionFactory.getCurrentSession();        //创建事务对象        Transaction tx=session.beginTransaction();        Students s1=new Students("s0000001","小明","男",new Date(),"成都");        session.save(s1);        tx.commit();        sessionFactory.close();    }}
    获得Configuration    创建SessionFactory    打开Session    开启事务    使用session操作数据    提交事务    关闭资源