Announcement Announcement Module
Collapse
No announcement yet.
nullpointer exception from getHibernateTemplate().execute() Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • nullpointer exception from getHibernateTemplate().execute()

    Hi,

    I am trying to insert data into database using hibernate. I did the following steps.

    1. I used postgres database. I created the table "Person". I used the following query
    Code:
    create table PERSON
    (
    	ID numeric NOT NULL,
    	NAME character varying(200),
    	SURNAME character varying(200),
    	BIRTHDATE date,
    	SEX character varying(200),
    	CONSTRAINT PERSON_PKEY PRIMARY KEY (ID)
    );
    2. I used the following hbm.xml mapping file
    Code:
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <!-- Generated Jul 15, 2011 10:15:12 AM by Hibernate Tools 3.2.1.GA -->
    <hibernate-mapping>
    <!-- <class name="gr.persons.entities.Person" dynamic-update="false" dynamic-insert="false" table="PERSON">
        	 <cache usage="read-write"/> 
            <id name="id" access="field">
                <column name="ID" sql-type="bigserial" length="8" not-null="true"/>
                 <generator class="native" /> 
                 
            </id> -->
    
        <class name="main.Person" table="PERSON">
            <id name="id" type="big_decimal">
                <column name="ID" precision="22" scale="0" />
                <generator class="assigned" />
            </id> 
            
            <property name="name" type="string">
                <column name="NAME" length="50" />
            </property>
            <property name="surname" type="string">
                <column name="SURNAME" length="50" />
            </property>
            <property name="birthdate" type="date">
                <column name="BIRTHDATE" length="7" />
            </property>
            <property name="sex" type="string">
                <column name="SEX" length="8" />
            </property>
        </class>
    </hibernate-mapping>
    3. my hibernate.cfg.xml file
    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <!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>
      <!-- Database connection settings -->
      <property name="connection.driver_class">org.postgresql.Driver</property>
      <property name="connection.url">jdbc:postgresql://localhost:5432/cemdb</property>
      <property name="connection.username">postgres</property>
      <property name="connection.password">NotAllowed@123</property>
       
      <!-- JDBC connection pool (use the built-in) -->
      <property name="connection.pool_size">1</property>
       
      <!-- SQL dialect -->
      <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
       
      <!-- Enable Hibernate's automatic session context management -->
      <property name="current_session_context_class">thread</property>
     
      <!-- Disable the second-level cache -->
      <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
       
      <!-- Echo all executed SQL to stdout -->
      <property name="show_sql">true</property>
       
      <!-- Drop and re-create the database schema on startup -->
      <property name="hbm2ddl.auto">update</property>
       
      <!--  Mapping files -->
         <mapping resource="Person.hbm.xml"/>
       
     </session-factory>
    </hibernate-con
    4. my main class
    Code:
    package main;
    
    import java.math.BigDecimal;
    import java.sql.Timestamp;
    
    
    public class Main {
    
       
        public static void main(String[] args) {
            
    		PersonManager personManager = new PersonManagerImpl();
    		Person p = new Person(BigDecimal.valueOf(7), "weada", "dassda", null, "Male");
            personManager.saveNewPerson(p);
    	
        }
    
    }
    5. entity class. Person.java
    Code:
    package main;
    // Generated Jul 15, 2011 10:15:10 AM by Hibernate Tools 3.2.1.GA
    
    
    import java.math.BigDecimal;
    import java.util.Date;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;
    
    /**
     * Person generated by hbm2java
     */
    @Entity
    @Table(name="PERSON"
        ,schema="YOUR_SCHEMA"
    )
    public class Person  implements java.io.Serializable {
    
    
         private BigDecimal id;
         private String name;
         private String surname;
         private Date birthdate;
         private String sex;
    
        public Person() {
        }
    
    	
        public Person(BigDecimal id) {
            this.id = id;
        }
        public Person(BigDecimal id, String name, String surname, Date birthdate, String sex) {
           this.id = id;
           this.name = name;
           this.surname = surname;
           this.birthdate = birthdate;
           this.sex = sex;
        }
       
         @Id 
        
        @Column(name="ID", unique=true, nullable=false, precision=22, scale=0)
        public BigDecimal getId() {
            return this.id;
        }
        
        public void setId(BigDecimal id) {
            this.id = id;
        }
        
        @Column(name="NAME", length=50)
        public String getName() {
            return this.name;
        }
        
        public void setName(String name) {
            this.name = name;
        }
        
        @Column(name="SURNAME", length=50)
        public String getSurname() {
            return this.surname;
        }
        
        public void setSurname(String surname) {
            this.surname = surname;
        }
        @Temporal(TemporalType.DATE)
        @Column(name="BIRTHDATE", length=7)
        public Date getBirthdate() {
            return this.birthdate;
        }
        
        public void setBirthdate(Date birthdate) {
            this.birthdate = birthdate;
        }
        
        @Column(name="SEX", length=8)
        public String getSex() {
            return this.sex;
        }
        
        public void setSex(String sex) {
            this.sex = sex;
        }
    
    
    
    
    }
    6. manager class (which calls the method saveorupdate in generichibernatedao.java)
    Code:
    package main;
    
    
    import java.math.BigDecimal;
    import java.util.ArrayList;
    import java.util.List;
    import javax.persistence.NonUniqueResultException;
    import org.hibernate.HibernateException;
    
    
    
    public class PersonManagerImpl implements PersonManager {
    	
        private PersonDAO personDAO = new PersonDAOImpl();
    
        public void saveNewPerson(Person person) {
        	//public void saveNewPerson(T entity) {
            try {
                
                personDAO.saveOrUpdate(person);
               
            } catch (HibernateException ex) {
                System.out.println("Handle your error here");
               
            }
        }
    }
    7. GernericHibernateDao.java (copy pasted a part of file, full file is in the attachment)
    Code:
    package main;
    //package semina.generic.dao;
    
    import java.io.Serializable;
    import java.sql.SQLException;
    import java.util.List;
    
    import org.hibernate.Criteria;
    import org.hibernate.FlushMode;
    import org.hibernate.HibernateException;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    import org.hibernate.criterion.Criterion;
    import org.hibernate.criterion.DetachedCriteria;
    import org.hibernate.criterion.Example;
    import org.hibernate.criterion.Restrictions;
    import org.springframework.orm.hibernate3.HibernateCallback;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    /**
     * 
     */
    public class GenericHibernateDao<T, ID extends Serializable> extends HibernateDaoSupport
    											implements GenericDao<T, ID> {
    
    	private Class<T> persistentClass;
    
    	public GenericHibernateDao(Class<T> persistentClass) {
    		this.persistentClass = persistentClass;
    //			(Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    	}
    
    	public Class<T> getPersistentClass(){
    		return persistentClass;
    	}
    
    	
    	public void saveOrUpdate(final T entity) {
    		getHibernateTemplate().executeWithNativeSession(
                    new HibernateCallback()
                    {
                        public Object doInHibernate(Session session) throws HibernateException
                        {
                            Transaction tx = session.beginTransaction();
                            
                            tx.begin();
                            session.save(entity);
                            tx.commit();
                            session.close();
                            return null;
                        }
                    }
                    );
    		/*getHibernateTemplate().execute(new HibernateCallback(){
    			public Object doInHibernate(Session session) throws HibernateException, SQLException {
    				session.saveOrUpdate(entity);
    				return null;
    			}
    		});*/
    	}
    
    	public void update(final T entity) {
    		getHibernateTemplate().execute(new HibernateCallback(){
    			public Object doInHibernate(Session session) throws HibernateException, SQLException {
    				session = getSessionFactory().getCurrentSession();
    				session.update(entity);
    				return null;
    			}
    		});
    	}
    
    }
    Attached is the package "main" which has all the files.

    when i try to run the main.java, the control goes to saveorupdate() in generichibernatedao.java to store the values of the persistent object into the database. but i am getting a nullpointer exception when i try to do so.

    Please help

  • #2
    solved. your dao entry should be added in the applicationcontext.xml

    Comment

    Working...
    X