hibernate连接数据库文件
                            

hibernate.cfg.xml
<?xml version="1.0" encoding="GB2312" ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name=
"hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>  
    <property name=
"hibernate.connection.url">jdbc:mysql://localhost/
struts?useUnicode=true&characterEncoding=latin1</property>
    <property name=
"hibernate.connection.username">root</property>
    <property name=
"hibernate.connection.password">123456</property>
    
    <property name=
"show_sql">true</property>
    <property name=
"dialect">net.sf.hibernate.dialect.MySQLDialect</property>
    <mapping resource=
"hb/User.hbm.xml" />
  </session-factory>
</hibernate-configuration>

HibernateUtil.java
package hb;

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (HibernateException ex) {
            throw new RuntimeException(
"Exception building SessionFactory: "
+ ex.getMessage(), ex);
        }
    }


    public static final ThreadLocal session = new ThreadLocal();

    public static Session currentSession() throws HibernateException {
      
//   Session s;
        Session s = (Session) session.get();
        
// Open a new Session, if this Thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
           session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null)
            s.close();
    }

}



      
      
lunzi   2006-05-23 23:29:44 评论:0   阅读:2375   引用:0

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2008 powered by YuLog