简体   繁体   English

Hibernate的示例程序中的java.lang.NullPointerException

[英]java.lang.NullPointerException in a sample program of Hibernate

i am try to run a sample application of hibernate, it give me a error on run time: 我试图运行一个休眠的示例应用程序,它在运行时给我一个错误:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN找不到记录器(org.hibernate.cfg.Environment)的附加程序。
log4j:WARN Please initialize the log4j system properly. log4j:WARN请正确初始化log4j系统。
Exception in thread "main" java.lang.NullPointerException at transaction.rollback(); transaction.rollback();处的线程“ main”中的异常java.lang.NullPointerException

this is in Main.java: 这在Main.java中:

public class Main {

public static void main(String[] args) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
        transaction = session.beginTransaction();
        Address address = new Address("ABC", "Delhi", "TN", "110001");
        Student student = new Student("kumar", address);
        session.save(student);
        transaction.commit();
    } catch (HibernateException e) {
        transaction.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }

Should change 应该改变

transaction.rollback();

to

if (transaction != null) {
    transaction.rollback();
}

as its possible for the assignment of transaction to throw an exception. 尽可能使事务分配引发异常。

If you want to get rid of the Log4J messages, you can add a call to 如果要摆脱Log4J消息,可以添加一个呼叫到

BasicConfigurator.configure();

to setup basic logging 设置基本日志

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM