SessionFactory在Hibernate5 Spring 4.2

时间:2015-10-01 21:31:53

标签: java spring hibernate nullpointerexception

我有一个名为PersistenceJPAConfig的Java Config类,我在其中配置与持久性相关的内容(会话工厂,事务等), 与UserService通信的UserDAO类,使用SessionFactory中的方法从数据库中获取所有用户。

理论上一切似乎都很美妙。但是,当我尝试获取这些用户时:抛出“NullPointerException”。

有没有人有线索?

配置类

@Configuration
@EnableTransactionManagement
public class PersistenceJPAConfig {


@Bean
public SessionFactory sessionFactory(){

    LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource());

    sessionBuilder.scanPackages("com.br.modelar.Modelar.model").addProperties(additionalProperties());
    SessionFactory sessionFactory = sessionBuilder.buildSessionFactory();

    return sessionFactory;
}

@Bean
public HibernateTransactionManager transactionManager(){

    HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory());
    return transactionManager;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

    LocalContainerEntityManagerFactoryBean manager = new LocalContainerEntityManagerFactoryBean();
    JpaVendorAdapter adapter = new HibernateJpaVendorAdapter();

    manager.setDataSource(dataSource());
    manager.setPackagesToScan("com.br.modelar.Modelar.model");
    manager.setJpaVendorAdapter(adapter);
    manager.setJpaProperties(additionalProperties());

    return manager;
}

@Bean
public DataSource dataSource() {

    DriverManagerDataSource dataSource = new DriverManagerDataSource();

    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/modelar_test");
    dataSource.setUsername("root");
    dataSource.setPassword("");

    return dataSource;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}

Properties additionalProperties() {
    Properties properties = new Properties();

    properties.put("hibernate.query.factory_class","org.hibernate.hql.classic.ClassicQueryTranslatorFactory");
    properties.put("hibernate.hbm2ddl.auto", "create-drop");
    properties.put("hibernate.dialect",
            "org.hibernate.dialect.MySQL5Dialect");
    return properties;
}

}

UserService类

@Service("userService")
public class UserService implements ServiceInterface<User, Integer>{

private HibernateUserDAO userDAO;

public UserService() {
    userDAO = new HibernateUserDAO();
}
@Override
public List<User> getAll() {

    return userDAO.getAll();
}
}

DAO课程

@Repository
public class HibernateUserDAO implements DAOInterface<User, Integer>{

@Autowired
private SessionFactory sessionFactory;

@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
@Override
public List<User> getAll() {

    List<User> users = sessionFactory.getCurrentSession().createQuery("SELECT FROM mduser").list();

    return users;
}
}

堆栈跟踪

java.lang.NullPointerException
com.br.modelar.Modelar.dao.HibernateUserDAO.getAll(HibernateUserDAO.java:50)
com.br.modelar.Modelar.service.UserService.getAll(UserService.java:44)
com.br.modelar.Modelar.controller.AdminController.viewUsers(AdminController.java:69)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

管理控制器 - 调用getAll()

@Controller
public class AdminController {


    @RequestMapping(value = "/view_users")
public ModelAndView viewUsers() {

    ModelAndView model = new ModelAndView("admin/show_users");
    //UserDAO dao = new UserDAO();

    //List<User> users = dao.getAll();

    UserService service = new UserService();
    List<User> users = service.getAll();

    model.addObject("users", users);
    return model;
}
}

1 个答案:

答案 0 :(得分:0)

session.createQuery(query)需要有效的HQL查询字符串。我不是HQL专家,但我认为"SELECT FROM mduser"是错误的。试试这个:

List<User> users = sessionFactory.getCurrentSession().createQuery("FROM mduser").list();

Spring可能不会扫描HibernateUserDAO。确保Spring正在使用您的DAO扫描包。 (另外发布代码是你打电话getAll()会很有用)

ok ...在您上次编辑之后,问题是:

UserService service = new UserService();

private HibernateUserDAO userDAO;

UserService是由Spring管理的bean:你不能像那样创建它。你必须注入以下内容:

@Autowired
private UserService userService;

当你使用注入(而不是显式的instanciation)时,对象是由Spring创建的,春天要注意正确地初始化它(通过在你的情况下注入userDAO - 见下一点)。

下一步

private HibernateUserDAO userDAO;

userDao没有注释:Spring不会对该字段做任何事情,这是一个问题。您必须添加注释:

@Autowired
private HibernateUserDAO userDAO;
public UserService() {
    //nothing here
}

作为一般规则:永远不要自己实例化bean:Spring为你做! (任何使用@ Repository注释的类,@ Service,@ Component ... - 还有更多 - 是一个bean。)