简体   繁体   中英

SessionFactory - I can't use buildSessionFactory function

    public static void main(String[]arg)
    {
        Session session = null;

        try{
            @SuppressWarnings("deprecation")
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session =sessionFactory.openSession();

            Contact contact = new Contact();
            contact.setID(3);
            contact.setFirstName("Professor");
            contact.setLastName("Katagawa");
            contact.setEmail("Bradsis@yahoo.com");
            session.save(contact);
            System.out.println("Done");
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
        finally
        {        
            session.flush();
            session.close();
        }
    }

i always get an NullPointer exception at the session.flush(). I already have a class Contact defined as follows,

public class Contact
{
    private String firstName;
    private String lastName;
    private String email;
    private int id;

    public String getEmail()
    {
        return email;
    }

    public String getLastName()
    {
        return lastName;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public int getID()
    {
        return id;
    }

    public void setID(int ID)
    {   id=ID;  }

    public void setEmail(String e)
    {
        email=e;
    }

    public void setFirstName(String fn)
    {
        firstName=fn;
    }

    public void setLastName(String ln)
    {
        lastName=ln;
    }
}

The line SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); in the main method is reported as deprecated. I also have a correct mapping file. Thank you so much for any help.

There are two errors in your code:

1) In the finally clause you use the session instance without further check - but the instance only is available if the first two lines of your code were executed successfully. So either surround the flush() and close() with a if (session != null) or begin the try block two lines later.

2) After an exception the session can't be used any more; especially it is impossible to save objects or flush the session. This means, your flush() and close() should be in the normal block after session.save() and not in the finally clause.

If none of these two solves the problem: Please post the error message of your NullPointerException with a few lines of the stack trace and also post the output (is there the "Done" or a second exception which is eaten by your catch clause?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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