实体管理器Null指针异常 - java代码配置

时间:2018-02-08 23:34:32

标签: java spring hibernate model-view-controller

我试图使用Spring MVC和Hibernate构建WebApp。所有配置都是通过java代码(没有XML配置文件)。

当我使用实体管理器(在下面的帖子中使用的示例)时,它会在persist方法上抛出空指针异常 - 但是如果我在实体管理器上使用select查询它可以正常工作。

这是我的MVC配置:

package com.test.Config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class SpringWebAppInitializer implements WebApplicationInitializer{

public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext appContext = new 
        AnnotationConfigWebApplicationContext();
        appContext.register(ApplicationContextConfig.class);

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
                "SpringDispatcher", new DispatcherServlet(appContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");     
    }

}

ApplicationContextConfig.java:

package com.test.Config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@ComponentScan({"com.Test.Controllers"})
@EnableTransactionManagement
public class ApplicationContextConfig {

     private Properties getHibernateProperties() {
         Properties properties = new Properties();
         properties.put("hibernate.show_sql", "true");
         properties.put("hibernate.dialect", 
         "org.hibernate.dialect.MySQLDialect");
         return properties;
     }

    @Bean(name = "viewResolver")
    public InternalResourceViewResolver getViewResolver() {
         InternalResourceViewResolver viewResolver = 
         new InternalResourceViewResolver();
         viewResolver.setPrefix("/WEB-INF/views/");
         viewResolver.setSuffix(".jsp");
         return viewResolver;
    }


    @Bean(name = "dataSource")
    public DataSource getDataSource() {
         BasicDataSource dataSource = new BasicDataSource();
         dataSource.setDriverClassName("com.mysql.jdbc.Driver");
         dataSource.setUrl("jdbc:mysql://localhost:3306/mydb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
         dataSource.setUsername("root");
         dataSource.setPassword("admin");

         return dataSource;
    }


    @Autowired
    @Bean(name = "sessionFactory")
    public SessionFactory getSessionFactory(DataSource dataSource) {

         LocalSessionFactoryBuilder sessionBuilder = 
         new LocalSessionFactoryBuilder(dataSource);

         sessionBuilder.scanPackages("com.Test.Models");
         sessionBuilder.addProperties(getHibernateProperties());

         return sessionBuilder.buildSessionFactory();
    }

    @Autowired
    @Bean(name = "transactionManager")
    public HibernateTransactionManager getTransactionManager(
        SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = 
        new HibernateTransactionManager(sessionFactory);

        return transactionManager;
    }   

}

以下是使用实体管理器的示例:

package com.Test.TestPackage;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import com.Test.Models.User;

@Transactional
public class TestEntityManager {

     @PersistenceContext
     private EntityManager entityManager; 

     public void addUser(User tmp) {
          // throws null pointer exception  
          entityManager.persist(tmp);   
     }

     public User QueryUser(int id){
          // works fine
          List results = entityManager.createQuery("select u from User u 
          where u.Id = :id", User.class).setParameter("id", id)
                                        .getResultList();

          if(results.isEmpty()) return null; 
          else return (User) results.get(0); 
    }       

}

我的配置中缺少什么或我做错了什么?

非常感谢!

0 个答案:

没有答案