HTTP状态500 - 请求处理失败;重构Service类后,嵌套异常是java.lang.NullPointerException

时间:2015-09-15 09:51:05

标签: java spring hibernate model-view-controller

早期我有两个服务PersonService和ActionService但现在我认为只有一个服务更好。我构建它,但是当我运行我的应用程序时,我得到一个NullPointerException。有人可以帮忙吗?

下面的控制器类

@Service
@Transactional
public class UserServiceImpl implements UserService {

private static Logger LOGGER = Logger.getLogger("UserService");

@Autowired
private SessionFactory sessionFactory;

public List<User> getAll() {

    LOGGER.debug("Retrieving all users");
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("from User ");
    return query.list();

}

public List<Actions> getListOfActions(User user) {

    LOGGER.debug("Retriving all user actions");
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("from Actions where  user = " +   
user.getId());
    return query.list();
}


public User get(Integer id) {

    Session session = sessionFactory.getCurrentSession();
    User user = (User) session.get(User.class, id);
    return user;

}

public void add(User user) {

    LOGGER.debug("Adding new user");
    Session session = sessionFactory.getCurrentSession();
    Actions actions = new Actions();
    actions.setActionType(ActionType.ADDING_NEW_USER);
    actions.setDate(new Date());
    actions.setUser(user);
    user.getActions().add(actions);
    session.save(user);
    session.save(actions);

}

public void delete(Integer id) {

    LOGGER.debug("Deleting existing user");
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("from User where id = " + id);
    User user = (User) query.uniqueResult();
    List<Actions> actions = user.getActions();
    session.delete(user);
    for(Actions actionses: actions ){
        session.delete(actionses);
    }

}

public void edit(User user) {

    LOGGER.debug("Editing existing user");
    Session session = sessionFactory.getCurrentSession();
    User existingUser = (User) session.get(User.class, user.getId());
    existingUser.setLogin(user.getLogin());
    existingUser.setPassword(user.getPassword());
    existingUser.setReal_name(user.getReal_name());
    Actions actions = new Actions();
    actions.setActionType(ActionType.EDITING_EXISTING_USER);
    actions.setDate(new Date());
    actions.setUser(user);
    user.getActions().add(actions);

    session.save(existingUser);

}
}

下面的服务类

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context- 
3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />

<!-- Scans the classpath for annotated components that will be  
auto-registered as Spring beans.
 For example @Controller and @Service. Make sure to set the correct 
base-package-->
<context:component-scan base-package="com.oleg.project" />

<!-- Configures the annotation-driven Spring MVC Controller programming  
model.-->
<mvc:annotation-driven />

<!-- Load Hibernate related configuration -->
<import resource="hibernate-context.xml" />

</beans>

应用上下文

SEVERE: Servlet.service() for servlet [spring] in context with path []  
threw exception [Request processing failed; nested exception is  
java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.oleg.project.services.UserServiceImpl.add(UserServiceImpl.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy24.add(Unknown Source)
at com.oleg.project.controller.MainController.add(MainController.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

这是StackTrace

getElementsAtEvent

2 个答案:

答案 0 :(得分:0)

当看到像user.getActions().add(actions);这样的代码时,我总是感到难过。您现在正在暴露内部状态并让它被外界修改。可能还有setActions()方法可以执行类似这样的操作

public void setActions(Collection actions) {
    this.actions=actions;
}

这可以完全搞砸你的托管对象和集合,并混淆休眠。你永远不应该这样做。而是在您的用户上添加addActionremoveAction方法,并始终使用空集合初始化actions集合。 (我在这里使用的示例假设您使用的是Set

public class User {

    @OneToMany(mapedBy="user", cascade=ALL, orphanRemoval=true)
    private final Set<Actions> actions = new HashSet<Actions>();

     // Getter only, no setter!
     public Set<Actions> getActions() {
         return Collections.unmodifiableSet(this.actions);
     }

     public void addActions(Actions actions) {
          this.actions.add(actions);
          actions.setUser(this); // Only if bi-directional relation
     }

     public void removeActions(Actions actions) {
          this.actions.remove(actions);
          actions.setUser(null);
     }
}

另请注意用户的@OneToMany注释。有了这个,您只需要保存或删除User而不是单个Actions实体。这基本上现在已正确映射和管理。

您的add方法可能看起来像这样。

public void add(User user) {

    LOGGER.debug("Adding new user");
    Session session = sessionFactory.getCurrentSession();
    Actions actions = new Actions();
    actions.setActionType(ActionType.ADDING_NEW_USER);
    actions.setDate(new Date());
    user.addActions(actions);
    session.save(user);
}

删除更简单。

public void delete(Integer id) {

    LOGGER.debug("Deleting existing user");
    Session session = sessionFactory.getCurrentSession();
    User user = (User) session.get(User.class, id);
    session.delete(user);
}

您当然需要相应地修改其他方法。

您拥有的代码是(IMHO)不正确的集合管理和实体映射的标志。

答案 1 :(得分:0)

这可能不是你的情况,但可能对另一个有同样挑战的人有帮助。

我忘了给我的pom添加mysql依赖。如果那是你的情况,请将它添加到你的pom中

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.31</version>
</dependency>
相关问题