hibernate3在javaSE中的應用

1、加載hibernate3的jar包

 

2、創建hibernate的配置文件    在src目錄下創建hibernate.cfg.xml,內容如下,

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

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>
 <session-factory>
  <property name="dialect">
   org.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/Studentback.hbm.xml" />
  <mapping resource="com/aoli/model/Student.hbm.xml" />
  <mapping resource="com/aoli/model/Conuser.hbm.xml" />
 </session-factory>
</hibernate-configuration>

 

3、創建實體類以及實體類對應的映射文件 Student.java       Student.hbm.xml

Student.java 

package com.aoli.model;

import java.math.BigDecimal;

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

public class Student implements java.io.Serializable {

 // Fields

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

 // Constructors

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

 /** minimal constructor */
 public Student(BigDecimal sn, String sid) {
  this.sn = sn;
  this.sid = sid;
 }

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

 // Property accessors

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

 public void setSn(BigDecimal 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;
 }

}

 

Student.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.aoli.model.Student" table="STUDENT" schema="AOLI">
        <id name="sn" type="big_decimal">
            <column name="SN" precision="22" scale="0" />
            <generator class="assigned" />
        </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加載工廠類  HibernateSessionFactory.java

package com.aoli.config;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.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 org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

 static {
     try {
   configuration.configure(configFile);
   sessionFactory = configuration.buildSessionFactory();
  } 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 org.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的factory對象,鏈接數據庫

BaseHibernateDAO.java

 

package com.aoli.model;

import com.aoli.config.HibernateSessionFactory;
import org.hibernate.Session;


/**
 * Data access object (DAO) for domain model
 * @author MyEclipse Persistence Tools
 */
public class BaseHibernateDAO {
 
 public Session getSession() {
  return HibernateSessionFactory.getSession();
 }
 
}

 

6、創建實體類的dao類,操作對象在數據庫中進行添加,刪除,修改    StudentDAO.java

package com.aoli.model;

import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A data access object (DAO) providing persistence and search support for
 * Student entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 *
 * @see com.aoli.model.Student
 * @author MyEclipse Persistence Tools
 */

public class StudentDAO extends BaseHibernateDAO {
 private static final Logger log = LoggerFactory.getLogger(StudentDAO.class);
 // property constants
 public static final String SID = "sid";
 public static final String SNAME = "sname";
 public static final String SSEX = "ssex";
 public static final String SREMARK = "sremark";

 public void save(Student transientInstance) {
  log.debug("saving Student instance");
  try {
   getSession().save(transientInstance);
   log.debug("save successful");
  } catch (RuntimeException re) {
   log.error("save failed", re);
   throw re;
  }
 }

 public void delete(Student persistentInstance) {
  log.debug("deleting Student instance");
  try {
   getSession().delete(persistentInstance);
   log.debug("delete successful");
  } catch (RuntimeException re) {
   log.error("delete failed", re);
   throw re;
  }
 }

 public Student findById(java.math.BigDecimal id) {
  log.debug("getting Student instance with id: " + id);
  try {
   Student instance = (Student) getSession().get(
     "com.aoli.model.Student", id);
   return instance;
  } catch (RuntimeException re) {
   log.error("get failed", re);
   throw re;
  }
 }

 public List findByExample(Student instance) {
  log.debug("finding Student instance by example");
  try {
   List results = getSession()
     .createCriteria("com.aoli.model.Student").add(
       Example.create(instance)).list();
   log.debug("find by example successful, result size: "
     + results.size());
   return results;
  } catch (RuntimeException re) {
   log.error("find by example failed", re);
   throw re;
  }
 }

 public List findByProperty(String propertyName, Object value) {
  log.debug("finding Student instance with property: " + propertyName
    + ", value: " + value);
  try {
   String queryString = "from Student as model where model."
     + propertyName + "= ?";
   Query queryObject = getSession().createQuery(queryString);
   queryObject.setParameter(0, value);
   return queryObject.list();
  } catch (RuntimeException re) {
   log.error("find by property name failed", re);
   throw re;
  }
 }

 public List findBySid(Object sid) {
  return findByProperty(SID, sid);
 }

 public List findBySname(Object sname) {
  return findByProperty(SNAME, sname);
 }

 public List findBySsex(Object ssex) {
  return findByProperty(SSEX, ssex);
 }

 public List findBySremark(Object sremark) {
  return findByProperty(SREMARK, sremark);
 }

 public List findAll() {
  log.debug("finding all Student instances");
  try {
   String queryString = "from Student";
   Query queryObject = getSession().createQuery(queryString);
   return queryObject.list();
  } catch (RuntimeException re) {
   log.error("find all failed", re);
   throw re;
  }
 }

 public Student merge(Student detachedInstance) {
  log.debug("merging Student instance");
  try {
   Student result = (Student) getSession().merge(detachedInstance);
   log.debug("merge successful");
   return result;
  } catch (RuntimeException re) {
   log.error("merge failed", re);
   throw re;
  }
 }

 public void attachDirty(Student instance) {
  log.debug("attaching dirty Student instance");
  try {
   getSession().saveOrUpdate(instance);
   log.debug("attach successful");
  } catch (RuntimeException re) {
   log.error("attach failed", re);
   throw re;
  }
 }

 public void attachClean(Student instance) {
  log.debug("attaching clean Student instance");
  try {
   getSession().lock(instance, LockMode.NONE);
   log.debug("attach successful");
  } catch (RuntimeException re) {
   log.error("attach failed", re);
   throw re;
  }
 }
}

 7、在類中使用

package com.aoli.action;

import com.aoli.hibernate.HibernateSessionFactory;
import com.aoli.model.Student;
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();
   // //根據配置文件生成事務工廠 
   Transaction tsc = session.beginTransaction();

   Student st = new Student();
   st.setSid("B001");
   st.setSname("Aoli");
   st.setSname("XXX");
   st.setSremark("Hibernate 測試說明");
   st.setSsex("XX");
   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;
 }

}

 

 

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