0

The sessionFactory Bean which is autowired in my DAO is always showingup to be null. below is my project.

 import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Import;
    import org.springframework.core.io.ClassPathResource;

    @Configuration
    @Import({HibernateConfig.class})
    public class AppConfig {

        @Bean
        public PropertyPlaceholderConfigurer propertyPlaceHolderConfigurer(){
            PropertyPlaceholderConfigurer prop = new PropertyPlaceholderConfigurer();
            prop.setLocation(new ClassPathResource("dbProperties.properties"));
            prop.setIgnoreUnresolvablePlaceholders(true);
            return prop;

        }

    }


import java.util.Properties;
    import javax.sql.DataSource;
    import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import     org.springframework.transaction.annotation.EnableTransactionManagement;

import com.model.Person;

@Configuration
//@EnableTransactionManagement
//@PropertySource(value={"classpath:dbProperties.properties"})
public class HibernateConfig {

    @Value("${driverClassName}")
    private String driverClassName;
    @Value("${url}")
    private String url;
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;

    @Value("${hibernate.dialect}")
    private String hibernateDielect;
    @Value("${hibernate.show_sql}")
    private String hibernateShowSQL;
    @Value("${hibernate.hbm2ddl.auto}")
    private String hibernateHbm2Ddlauto;

    @Bean
    public DataSource datasource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);

        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    public Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", hibernateDielect);
        properties.put("hibernate.show_sql", hibernateShowSQL);
        properties.put("hibernate.hbm2ddl.auto", hibernateHbm2Ddlauto);
        return properties;

    }

    @Bean
    @Autowired
    public SessionFactory sessionFactory(DataSource dataSource) {

        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
        sessionBuilder.scanPackages("com.configuration");
        sessionBuilder.addAnnotatedClass(Person.class);
        sessionBuilder.addProperties(hibernateProperties());
        return sessionBuilder.buildSessionFactory();
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory);
        return transactionManager;
    }

}







 import java.util.List;

    import com.model.Person;

    public interface PersonDao {

        void savePerson(Person persom);
        void deletePerson(String taxid);
        List<Person> getAllPersons();
        Person updatePerson(Person person);
        Person findPersonById(String taxid);

    }



import java.util.List;

    import javax.transaction.Transactional;

    import org.hibernate.Criteria;
    import org.hibernate.Query;
    import org.hibernate.SessionFactory;
    import org.hibernate.criterion.Restrictions;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import com.model.Person;

    @Service
    public class PersonDaoImpl implements PersonDao {

        @Autowired
        SessionFactory sessionFactory;

        @Override
        @Transactional
        public void savePerson(Person person) {
            sessionFactory.getCurrentSession().persist(person);
        }

        @Override
        @Transactional
        public void deletePerson(String taxid) {
            // TODO Auto-generated method stub
            // Criteria criteria = getSession().createCriteria(Person.class);
            Query query = sessionFactory.getCurrentSession().createSQLQuery("DELETE FROM PERSON WHERE taxid = :taxid");
            query.setString(taxid, "taxid");

        }

        @SuppressWarnings("unchecked")
        @Override
        @Transactional
        public List<Person> getAllPersons() {
            // TODO Auto-generated method stub
            Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Person.class);
            return (List<Person>) criteria.list();
        }

        @Override
        @Transactional
        public Person updatePerson(Person person) {
            // TODO Auto-generated method stub
            sessionFactory.getCurrentSession().update(person);
            return person;
        }

        @Override
        @Transactional
        public Person findPersonById(String taxid) {
            // TODO Auto-generated method stub
            Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Person.class);
            criteria.add(Restrictions.eq("taxid", taxid));
            return (Person) criteria.uniqueResult();

        }

    }



import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name ="person")

public class Person {

    @Column(name ="FIRSTNAME")
    private String firstName;
    @Column(name ="LASTNAME")
    private String lastName;
    @Column(name ="DOB")
    private Date DOB;
    @Column(name ="TAXID")
    @Id
    private String taxid;

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Date getDOB() {
        return DOB;
    }
    public void setDOB(Date dOB) {
        DOB = dOB;
    }
    public String getTaxid() {
        return taxid;
    }
    public void setTaxid(String taxid) {
        this.taxid = taxid;
    }
    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + ", DOB=" + DOB + ", taxid=" + taxid + "]";
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((DOB == null) ? 0 : DOB.hashCode());
        result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
        result = prime * result + ((taxid == null) ? 0 : taxid.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (DOB == null) {
            if (other.DOB != null)
                return false;
        } else if (!DOB.equals(other.DOB))
            return false;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
            return false;
        if (taxid == null) {
            if (other.taxid != null)
                return false;
        } else if (!taxid.equals(other.taxid))
            return false;
        return true;
    }



}

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import com.configuration.AppConfig;
import com.dao.PersonDaoImpl;
import com.model.Person;

public class AppMain {

    public static void main(String args[]) {
        AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        Person person = new Person();
        person.setFirstName("Akhil");
        person.setLastName("goli");
        person.setTaxid("123abc456");

        PersonDaoImpl impl = new PersonDaoImpl();
        impl.savePerson(person);
        }
}

Exception in thread "main" java.lang.NullPointerException at com.dao.PersonDaoImpl.savePerson(PersonDaoImpl.java:25) at main.AppMain.main(AppMain.java:20)

halfer
  • 19,824
  • 17
  • 99
  • 186
juniorDeveloper
  • 225
  • 3
  • 18
  • Since your SessionFactory is Autowired, do you have a bean for it ? – Mickael Aug 05 '16 at 07:27
  • You should take a look to this : http://stackoverflow.com/questions/4128716/springhibernate-autowire-sessionfactory-into-hibernate-dao – Mickael Aug 05 '16 at 07:33
  • sorry I am new to java config. Upto what I understood below code creates a bean for sessionFactory. @Bean public SessionFactory sessionFactory(DataSource dataSource) { LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource); sessionBuilder.scanPackages("com.configuration"); sessionBuilder.addAnnotatedClass(Person.class); sessionBuilder.addProperties(hibernateProperties()); return sessionBuilder.buildSessionFactory(); } – juniorDeveloper Aug 05 '16 at 07:33
  • I was trying to implement with NoXML only javaConfig @MickaëlB – juniorDeveloper Aug 05 '16 at 07:37
  • Why is your method autowired ? – Mickael Aug 05 '16 at 07:38
  • I was following this tutorial http://sivalabs.in/2011/02/springhibernate-application-with-zero-xml/ please correct me guide me to solve this @MickaëlB – juniorDeveloper Aug 05 '16 at 07:40

3 Answers3

1

You have to call afterPropertiesSet() for initializing the bean. Now you only created the bean but not initialized.

Vipin CP
  • 3,642
  • 3
  • 33
  • 55
  • There is no afterPropertiesSet() method in LocalSessionFactoryBuilder class. Are you suggesting me to change it to LocalSessionFactoryBean ? @vipin – juniorDeveloper Aug 05 '16 at 07:52
0

I figured it out. As I was using Hibernate4 I need to use

StandardServiceRegistryBuilder class to get SessionFactory.

Hope this snippet helps.

public class HibernateUtil {

    public SessionFactory getSessionFactory()
    {
        Configuration config = new Configuration().configure();

        StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(config.getProperties());
        SessionFactory session = config.buildSessionFactory(serviceRegistryBuilder.build());
        return session;
    }
juniorDeveloper
  • 225
  • 3
  • 18
0

I am putting sessionFactory configuration code here. Hope it will help you.

    @Bean
    // @Autowired
    // @Bean(name = "sessionFactory")
    public SessionFactory sessionFactory() throws IOException {

        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
        hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
        hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);

        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
        sessionFactory.setHibernateProperties(hibernateProperties);
        sessionFactory.afterPropertiesSet(); // Used in Spring-boot 2.x for initializing the bean
        SessionFactory sf = sessionFactory.getObject();
        System.out.println("## getSessionFactory: " + sf);
        return sf;
    }
Prashant Sahoo
  • 979
  • 16
  • 19