使用javaconfig时,sessionfactory总是为null

时间:2016-08-05 07:20:56

标签: spring hibernate spring-annotations spring-java-config

在我的DAO中自动装配的sessionFactory Bean始终显示为null。下面是我的项目。

 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);
        }
}
  

线程“main”中的异常java.lang.NullPointerException at   com.dao.PersonDaoImpl.savePerson(PersonDaoImpl.java:25)at   main.AppMain.main(AppMain.java:20)

3 个答案:

答案 0 :(得分:1)

您必须调用afterPropertiesSet()来初始化bean。现在你只创建了bean但没有初始化。

答案 1 :(得分:0)

我明白了。当我使用Hibernate4时,我需要使用

StandardServiceRegistryBuilder类获取SessionFactory。

希望这段代码有所帮助。

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;
    }

答案 2 :(得分:0)

我将sessionFactory配置代码放在这里。希望对您有帮助。

    @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;
    }