hibernate实战

来源:互联网 发布:高性能javascript 编辑:程序博客网 时间:2024/06/06 18:30

离下班还有半个小时,写这个东东吧。

今天写了个hibernate实例。

第一步:向工程中添加hibernate的lib

          * HIBERNATE_HOME/hibernate3.jar

          * HIBERNATE_HOME/lib/*.jar

          * 数据库 jdbc驱动

第二步:写hibernate.cfg.xml文件如下,这里有连接数据库,设置数据库方言,注册类映射文件User.hbm.xml(后面会提到)

<hibernate-configuration>
<session-factory >
  <property name ="hibernate.connection.url">jdbc:mysql://localhost/hibernate_first</property>
  <property name ="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name ="hibernate.connection.username">root</property>
  <property name ="hibernate.connection.password">root</property>
  <property name ="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.show_sql">true</property>
  <mapping resource="com/bjsxt/hibernate/User.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

第三步:

写实体类,如User.java,实体类包括id,password这些字段,写映射文件User.hbm.xml如下:

<hibernate- mapping>
<class name="com.bjsxt.hibernate.User">
  <id name="id">
   <generator class="uuid"/>
  </id>
  <property name="name"></property>
  <property name="password"></property>
  <property name="createTime"></property>
  <property name="expireTime"></property> 
</class>
</hibernate-mapping>

第四步:工具类(数据库生成)

public class ExportDB {

public static void main(String[] args) {
  //读取hibernate.cfg.xml文件
  Configuration cfg = new Configuration().configure();
//数据库操作对象 

SchemaExport export = new SchemaExport(cfg);
//建表

export.create(true, true);
}

}

这里把hibernate核心配置文件中的对应类映射到数据库中的表,并完成建表操作

第五步:写应用类Client.java

public class Client {

public static void main(String[] args) {
  //读取hibernate.cfg.xml文件
  Configuration cfg = new Configuration().configure();
  //创建SessionFactory
  SessionFactory factory = cfg.buildSessionFactory();
  Session session = null;
  try{
   session = factory.openSession();
   //开启事物
   session.beginTransaction();
   User user = new User();
   user.setName("张三");
   user.setPassword("123");
   user.setCreateTime(new Date());
   user.setExpireTime(new Date());
   //保存事物
   session.save(user);
   session.getTransaction().commit();
  }catch(Exception e){
   e.printStackTrace();
   //回滚事物
   session.getTransaction().rollback();
  }finally{
   if(session !=null){
    if(session.isOpen()){
     //关闭session
     session.close();
    }
   }
  }
}

}

这个Client里面关键对象是session,它完成数据从实体中取出,并向数据库提交的工作。

使用了事物的编程模式,将实物放到session中,进行提交或者回滚操作。这一条xiao12经常提到,每次讲数据库操作都不忘说说,呵呵。

总体来说,hibernate的实现方法就是:1建实体类->2实体映射文件->3实体映射文件在hibernate配置文件中注册->4hibernate配置文件对数据库(不同数据库配置不同,今后需要换数据库只要在这里修改就可以了)连接进行配置->5建数据库导入类,将hibernate配置文件中注册了的实体写入数据库中,建表->6写应用程序,关键是sessionFactory的应用,对实体操作,然后commit到事物中。

OK,打完收工。

还有个十几分钟,嘿嘿,就要happy了。。。谄笑

原创粉丝点击