找不到正确保存onetomany关系记录的方法

时间:2016-06-09 05:57:50

标签: java spring-mvc spring-data-jpa

我想保存学生记录,并注明以下表格

<form:form commandName="std" method="POST" >             
         <form:input type="text" path="name"/>
         <label>Subjects</label>
         <form:select path="subjects" multiple="multiple">
            <form:option value="English">English</form:option>
            <form:option value="Maths">Maths</form:option>
         </form:select>

     <input type="submit" value="Save">
</form:form>

在控制器中我有一个活页夹

@InitBinder
public void initSubjectBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Subject.class,
    new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) {
            Subject subject = new Subject();
            subject.setSubjectName(text);
            System.out.println("Saving Subject Object...");
            subjectService.save(subject);               
        }
    });     
}

以上initSubjectBinder()保存了Subject对象,但主题未分配给Student。在POST方法中,我想将Student添加到选定的主题

@RequestMapping(value = "/save-std", method = RequestMethod.POST)
    public String saveStd(@ModelAttribute("std") Student std) {
        try {
            System.out.println("List size is " + std.getSubjects().size()); // Here it says List Size is 4 (if four subjects are selected)
            for (Subject subject : std.getSubjects()) {
                subject.setStudent(std); // Here it gives NPE see stackTrace for more info
                subjectService.update(subject);
            }
        } catch (Exception e) {
            System.out.println("Error is " + e.getMessage());
        }
        return "home";
    }

我在控制台中获得Hibernate结果

Saving Subject Object...
Hibernate: 
    insert 
    into
        Subject
        (studentId, subjectName) 
    values
        (?, ?)
Saving Subject Object...
Hibernate: 
    insert 
    into
        Subject
        (studentId, subjectName) 
    values
        (?, ?)
Saving Subject Object...
Hibernate: 
    insert 
    into
        Subject
        (studentId, subjectName) 
    values
        (?, ?)
Saving Subject Object...
Hibernate: 
    insert 
    into
        Subject
        (studentId, subjectName) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        Student
        (studentName) 
    values
        (?)
List size is 4 (Result of System.out.println("List size is " + std.getSubjects().size()); )
Error is null (Result of System.out.println("Error is " + e.getMessage());)

并且堆栈跟踪是

  

显示java.lang.NullPointerException           在com.app.web.HomeController.saveStd(HomeController.java:76)           at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)           at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)           at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)           at 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:110)           在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)           在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)           在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:966)           在org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)           在javax.servlet.http.HttpServlet.service(HttpServlet.java:650)           在org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)           在javax.servlet.http.HttpServlet.service(HttpServlet.java:731)           在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)           在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)           在org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)           在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)           在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)           在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)           在org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)           在org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)           在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)           在org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)           在org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)           在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)           在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)           在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:316)           at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)           at java.util.concurrent.ThreadPoolExecutor $ Worker.run(Unknown Source)           at org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)           在java.lang.Thread.run(未知来源)

现在很难理解NPE发生的地点和原因以及我应该如何为学生分配科目?

1 个答案:

答案 0 :(得分:0)

感谢@PavelHoral,他在做出一些改变之后指出了我的错误

@InitBinder
public void initSubjectBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Subject.class,
    new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) {
            Subject subject = new Subject();
            subject.setSubjectName(text);
            setValue(subject); // This is the turning point for me         
        }
    });     
}

和控制器方法

@RequestMapping(value = "/save-std", method = RequestMethod.POST)
    public String saveStd(@ModelAttribute("std") Student std) {
        try {
            System.out.println("List size is " + std.getSubjects().size()); 
            for (Subject subject : std.getSubjects()) {
                subject.setStudent(std); 
                subjectService.save(subject);
            }
        } catch (Exception e) {
            System.out.println("Error is " + e.getMessage());
        }
        return "home";
    }

它起作用,我的问题得到了解决。