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.java
public class HibernateUtil {
private static final SessionFactory sessionFactory;
//取得sessionFactory
static {
try {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException("Exception building SessionFactory: "
+ ex.getMessage(), ex);
}
}
//开启session
public static Session currentSession() {
Session s = sessionFactory.openSession();
return s;
}
//关闭session
public static void closeSession(Session s){
s.close();
}
}