hibernate2在web中的應用

1、拷貝hibernate2的jar包

 

2、在src目錄下創建hibernate.cfg.xml配置文件

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 2.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>
 <session-factory>
  <property name="dialect">
   net.sf.hibernate.dialect.Oracle9Dialect
  </property>
  <property name="connection.url">
   jdbc:oracle:thin:@localhost:1521:mydb
  </property>
  <property name="connection.username">aoli</property>
  <property name="connection.password">aoli</property>
  <property name="connection.driver_class">
   oracle.jdbc.driver.OracleDriver
  </property>
  <mapping resource="com/aoli/model/Student.hbm.xml" />
  <mapping resource="com/aoli/model/Studentback.hbm.xml" />
 </session-factory>
</hibernate-configuration>

 

3、創建實體類和映射文件  Studentback.java,Studentback.hbm.xml

Studentback.java

package com.aoli.model;

/**
 * Studentback entity. @author MyEclipse Persistence Tools
 */

public class Studentback implements java.io.Serializable {

 // Fields

 private Long sn;
 private String sid;
 private String sname;
 private String ssex;
 private String sremark;

 // Constructors

 /** default constructor */
 public Studentback() {
 }

 /** minimal constructor */
 public Studentback(String sid) {
  this.sid = sid;
 }

 /** full constructor */
 public Studentback(String sid, String sname, String ssex, String sremark) {
  this.sid = sid;
  this.sname = sname;
  this.ssex = ssex;
  this.sremark = sremark;
 }

 // Property accessors

 public Long getSn() {
  return this.sn;
 }

 public void setSn(Long sn) {
  this.sn = sn;
 }

 public String getSid() {
  return this.sid;
 }

 public void setSid(String sid) {
  this.sid = sid;
 }

 public String getSname() {
  return this.sname;
 }

 public void setSname(String sname) {
  this.sname = sname;
 }

 public String getSsex() {
  return this.ssex;
 }

 public void setSsex(String ssex) {
  this.ssex = ssex;
 }

 public String getSremark() {
  return this.sremark;
 }

 public void setSremark(String sremark) {
  this.sremark = sremark;
 }

}

Studentback.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.aoli.model.Studentback" table="STUDENTBACK" schema="AOLI">
        <id name="sn" type="long">
            <column name="SN"  />
            <generator class="sequence" >
              <param name="sequence">seq_studentback_sn</param>
            </generator>
        </id>
        <property name="sid" type="string">
            <column name="SID" length="20" not-null="true" />
        </property>
        <property name="sname" type="string">
            <column name="SNAME" length="20" />
        </property>
        <property name="ssex" type="string">
            <column name="SSEX" length="5" />
        </property>
        <property name="sremark" type="string">
            <column name="SREMARK" length="100" />
        </property>
    </class>
</hibernate-mapping>

4、創建hibernate的factory類,系統加載hibernate數據鏈接和實體映射  HibernateSessionFactory.java

HibernateSessionFactory.java

package com.aoli.hibernate;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /**
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses 
     * #resourceAsStream style lookup for its configuration file.
     * The default classpath location of the hibernate config file is
     * in the default package. Use #setConfigFile() to update
     * the location of the configuration file for the current session.  
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
 private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();   
    private static net.sf.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

 static {
     try {
   configuration.configure(configFile);
   sessionFactory = configuration.buildSessionFactory();
   System.out.println("========sessionFactory:"+sessionFactory);
  } catch (Exception e) {
   System.err.println("%%%% Error Creating SessionFactory %%%%");
   e.printStackTrace();
  }
    }
    private HibernateSessionFactory() {
    }
 
 /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
  if (session == null || !session.isOpen()) {
   if (sessionFactory == null) {
    rebuildSessionFactory();
   }
   session = (sessionFactory != null) ? sessionFactory.openSession(): null;
   threadLocal.set(session);
  }
        return session;
    }

 /**
     *  Rebuild hibernate session factory
     *
     */
 public static void rebuildSessionFactory() {
  try {
   configuration.configure(configFile);
   sessionFactory = configuration.buildSessionFactory();
  } catch (Exception e) {
   System.err
     .println("%%%% Error Creating SessionFactory %%%%");
   e.printStackTrace();
  }
 }

 /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

 /**
     *  return session factory
     *
     */
 public static net.sf.hibernate.SessionFactory getSessionFactory() {
  return sessionFactory;
 }

 /**
     *  return session factory
     *
     * session factory will be rebuilded in the next call
     */
 public static void setConfigFile(String configFile) {
  HibernateSessionFactory.configFile = configFile;
  sessionFactory = null;
 }

 /**
     *  return hibernate configuration
     *
     */
 public static Configuration getConfiguration() {
  return configuration;
 }

}

 

5、獲取hibernate工廠類,獲取數據鏈接,操作實例類在數據庫中的添加,刪除,修改操作  StudentAction

package com.aoli.action;

import com.aoli.hibernate.HibernateSessionFactory;
import com.aoli.model.Student;
import com.aoli.model.Studentback;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;

public class StudentAction {
 private Session session;
 public Session findSession() {
   try {
   session = HibernateSessionFactory.getSession();
  } catch (HibernateException e) {
   e.printStackTrace();
  }
  return session;
 }
 
 public Long studentbackServer(){
  try {
   findSession();
   // SessionFactory sf = cfg.configure().buildSessionFactory();
   // //根據配置文件生成事務工廠
   System.out.println("===========session:" + session);
   Transaction tsc = session.beginTransaction();

   Studentback st = new Studentback();
   st.setSid("B001");
   st.setSname("Aoli");
   st.setSname("李建成");
   st.setSremark("Hibernate 測試說明");
   st.setSsex("男");
   Long obj = (Long) session.save(st);
   session.flush();
   tsc.commit();
   // session.getSessionFactory()
   session.close();
   return obj;
  } catch (HibernateException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return 1l;
 }

}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章