Hibernate.cfg.xml,Session常用模板

来源:互联网 发布:橙树网络 编辑:程序博客网 时间:2024/06/05 22:49

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">

<hibernate-configuration>

    <session-factory>
       
        <property name="connection.dirver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/dbtest</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <!--指定连接的语言 -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <mapping resource="com/bean/Student.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

2、

在HibernateUtil.java 类中编写SessionFactory 的获得,以及Session 实例的打开和关闭代码,如下所示:// HibernateUtil.javapublic class HibernateUtil {private static final SessionFactory sessionFactory;//取得sessionFactorystatic {try {sessionFactory = new Configuration().configure().buildSessionFactory();} catch (HibernateException ex) {throw new RuntimeException("Exception building SessionFactory: "+ ex.getMessage(), ex);}}//开启sessionpublic static Session currentSession() {Session s = sessionFactory.openSession();return s;}//关闭sessionpublic static void closeSession(Session s){s.close();}}


 

原创粉丝点击