最近在学习hibernate,所用版本是hibernate-distribution-3.6.0.Final
1.在test运行时总会报错NullPointException,经过反复调试发现时在SessionFactory创建时没有给生成的Sessionfactory对象赋值。
HibernateUtils代码如下
package util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class HibernateUtil {
private static SessionFactory sf;
static {
sf = new Configuration().configure().buildSessionFactory();
}
public static Session getSession() {
Session session = sf.openSession();
return session;
}
}
2.在解决了这个问题之后改变了实体类Employee.java的路径,而忘记将配置文件Employee.hbm.xml放在同一个路径下,并且同步配置,结果第二次出现了NullPointException的异常,显示是在session.beginTransaction().commit()时没有事务对象。
总结一定要保证实体类和其配置文件在同一包目录下,并且同步配置文件。
配置文件及项目结构如下:
Employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="entity">
<class name="Employee" table="employee">
<id name="id" column="id"></id>
<property name="empName" column="empName"></property>
<property name="workDate" column="workDate"></property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate1</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="entity/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>