第一个hibernate项目

来源:互联网 发布:以下淘宝网禁售商品 编辑:程序博客网 时间:2024/04/27 19:10



1.将相应的jar包加入项目中,包括hibernate3核心包,lib下的所有文件,已经相应的数据库驱动。
2.创建hibernate的配置文件hibernate.cfg.xml
3.定义实体类
4.创建实体类对应的映射文件(类名.hbm.xml)
5.将实体类的映射文件加入到hibernate.cfg.xml中
6.创建工具类,将实体类创建成数据库表。
*读取hibernate.cfg.xml,如果不加.configure(),默认是先读取.property配置文件
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(true, true);
7.创建客户端。
//读取hibernate.cfg.xml
Configuration cfg = new Configuration().configure();
//创建sessionFactory
SessionFactory factory = cfg.buildSessionFactory();
//创建session
Session session = null;
try{
session= factory.openSession();
//开启事务
session.beginTransaction();
//保存对象
session.save(user);
//提交事务
session.getTransaction().commit();
}catch(Exception e){
e.printStackTrace();
//回滚事务
session.getTransaction().rollback();
}finally{
if(session != null){
if(session.isOpen()){
//关闭事务
session.close();
}
}
}

为了显示sql语句,在hibernate.cfg.xml文件中加入<property name="hibernate.show_sql">true</property>