hibernate 学习中的NullPointException解决

最近在学习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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值