I am new to hibernate.When i'm trying to call session.get() method then Nullpointer Exception is occurring.How can i fix it
My pojo class:-
package test;
import java.util.*;
public class user1 implements java.io.Serializable{
private int id;
private String name;
private String department;
private String password;
public user1() {}
public user1(int id,String name, String department, String password) {
this.id = id;
this.name = name;
this.department = department;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
My user1.hbm.xml file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="test.user1" table="users">
<id name="id" column="id" type="int">
</id>
<property name="name" column="name" type="string"/>
<property name="department" column="department" type="string"/>
<property name="password" column="password" type="string"/>
</class>
</hibernate-mapping>
I am calling session.get(user1.class,id) method in my updateUser() function. Nullpointer exception is thrown at runtime.
public class user2 {
private static SessionFactory factory;
public static void main(String [] args){
try{
factory = new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
System.err.println("SessionFactory object could not be created"+ex);
throw new ExceptionInInitializerError(ex);
}
user2 User = new user2();
//User.addUser(3,"cc","cse","cc");
//User.showUser();
User.updateUser(Integer.valueOf(3),"dd","cse","dd");
}
public void addUser(int id,String name,String department,String password){
Session session = factory.openSession();
Transaction t = null;
try{
t = session.beginTransaction();
user1 User1 = new user1(id,name,department,password);
session.save(User1);
t.commit();
}
catch (HibernateException e) {
if (t!=null) t.rollback();
e.printStackTrace();
}
finally {
session.close();
}
}
public void updateUser(Integer id,String name,String department,String password){
Session session = factory.openSession();
Transaction t = null;
try{
user1 user = (user1)session.get(user1.class,id);
user.setName(name);
user.setDepartment(department);
user.setPassword(password);
session.update(user);
t.commit();
}
catch (HibernateException e) {
if (t!=null) t.rollback();
e.printStackTrace();
}
finally {
session.close();
}
}
}
}