开发者

java.lang.NullPointerException in a sample program of Hibernate

开发者 https://www.devze.com 2023-01-11 13:35 出处:网络
i am try to run a sample开发者_如何学运维 application of hibernate, it give me a error on run time:

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 Please initialize the log4j system properly.

Exception in thread "main" java.lang.NullPointerException at transaction.rollback();

this is in 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

BasicConfigurator.configure();

to setup basic logging

0

精彩评论

暂无评论...
验证码 换一张
取 消