NullPointerException: null при попытке использовать jdbcTemplete - PullRequest
0 голосов
/ 03 октября 2019

Я пытаюсь в течение 2 дней решить мою проблему и понять, где я был не прав. Я пытаюсь использовать TodoService для отображения элементов в сетке и для добавления данных в мой SQL. но я получаю сообщение об ошибке:

Я просто набираю 4 поля в todoview и нажимаю кнопку сохранения (הוסף). Я догадываюсь о своей проблеме со службой. но я не понимаю, что. люди пытались мне помочь, но ничего не помогло.

java.lang.NullPointerException: null
    at com.packagename.ui.views.TodoView.saveTodo(TodoView.java:111) ~[classes/:na]
    at com.packagename.ui.views.TodoView.onComponentEvent(TodoView.java:127) ~[classes/:na]
    at com.vaadin.flow.component.ComponentEventBus.fireEventForListener(ComponentEventBus.java:205) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.component.ComponentEventBus.handleDomEvent(ComponentEventBus.java:373) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.component.ComponentEventBus.lambda$addDomTrigger$dd1b7957$1(ComponentEventBus.java:264) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.internal.nodefeature.ElementListenerMap.lambda$fireEvent$2(ElementListenerMap.java:441) ~[flow-server-2.0.14.jar:2.0.14]
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1507) ~[na:na]
    at com.vaadin.flow.internal.nodefeature.ElementListenerMap.fireEvent(ElementListenerMap.java:441) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.server.communication.rpc.EventRpcHandler.handleNode(EventRpcHandler.java:59) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.server.communication.rpc.AbstractRpcInvocationHandler.handle(AbstractRpcInvocationHandler.java:64) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.server.communication.ServerRpcHandler.handleInvocationData(ServerRpcHandler.java:378) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.server.communication.ServerRpcHandler.lambda$handleInvocations$1(ServerRpcHandler.java:359) ~[flow-server-2.0.14.jar:2.0.14]
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1507) ~[na:na]
    at com.vaadin.flow.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:359) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:301) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:87) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:40) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.server.VaadinService.handleRequest(VaadinService.java:1540) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.server.VaadinServlet.service(VaadinServlet.java:246) ~[flow-server-2.0.14.jar:2.0.14]
    at com.vaadin.flow.spring.SpringServlet.service(SpringServlet.java:95) ~[vaadin-spring-12.0.6.jar:na]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:750) ~[javax.servlet-api-4.0.1.jar:4.0.1]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:352) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.servlet.mvc.ServletForwardingController.handleRequestInternal(ServletForwardingController.java:141) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:177) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:52) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:665) ~[javax.servlet-api-4.0.1.jar:4.0.1]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:750) ~[javax.servlet-api-4.0.1.jar:4.0.1]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]

TodoService.java



@Component
public class TodoService {
@Autowired
    private JdbcTemplate jdbcTemplate;
    public List<Todo> findAll() {
        return jdbcTemplate.query(
                "SELECT ID, TaskStatus, dudate,subject FROM todo",
                (rs, rowNum) -> new Todo(rs.getLong("ID"),
                        rs.getLong("UserID"), rs.getLong("descriptionID"),rs.getString("taskstatus")));
    }

    public void update(Todo todo) {
        jdbcTemplate.update("INSERT INTO todo (TaskStatus,dudate,subject,CustomerID) VALUES(?,?,?,?)",todo.getTaskStatus(),todo.getDudate(),todo.getSubject(),todo.getCustomerID());


    }

}

Todo.java

public class Todo {
    private  long userID;
    private String taskstatus;
    private long ID;
    private long customerID;
    private long descriptionID;
    private String taskStatus;
    private String Subject;
    private LocalDate Dudate;

    public Todo() // Def Ctor
    {

    }

 public Todo (String taskstatus,LocalDate dudate,String subject,long customerid){

     this.customerID= customerid;
     this.Subject = subject;
     this.Dudate = dudate;
     this.taskstatus = taskstatus;
 }
    public Todo(long id, long customerid, long descriptionid, String task) { // Ctor all
        this.ID=id;
        this.customerID=customerid;
        this.descriptionID=descriptionid;
        this.taskStatus=task;

    }

    public long getID() {
        return ID;
    }

    public void setID(long ID) {
        this.ID = ID;
    }

    public long getUserID() {
        return userID;
    }

    public void setUserID(long userID) {
        this.userID = userID;
    }

    public long getDescriptionID() {
        return descriptionID;
    }

    public void setDescriptionID(long descriptionID) {
        this.descriptionID = descriptionID;
    }

    public String getTaskStatus() {
        return taskStatus;
    }

    public void setTaskStatus(String taskStatus) {
        this.taskStatus = taskStatus;
    }

    public String getSubject() {
        return Subject;
    }

    public void setSubject(String subject) {
        this.Subject = subject;
    }

    public LocalDate getDudate() {
        return Dudate;
    }

    public void setDudate(LocalDate dudate) {
        this.Dudate = dudate;
    }

    public long getCustomerID() {
        return customerID;
    }

    public void setCustomerID(long customerID) {
        this.customerID = customerID;
    }
}

TodoView.java

package com.packagename.ui.views;

@Route(value = NAV,layout = MainView.class)
public class TodoView extends Composite<Div> {
    public static final String NAV = "todo";
    public Todo todo = new Todo();
    private Grid<Todo> todogrid = new Grid<>(Todo.class);
    private Binder<Todo> binder = new Binder<>(Todo.class);
    @Autowired
    @SuppressWarnings( "SpringJavaAutowiredMembersInspection")
    private TodoService service ;

    private  Button addButton = new Button("Save", //   } catch (ValidationException ex) {
            //     ex.printStackTrace();
            this::onComponentEvent);

    public TodoView(){

        //Layouts//
        HorizontalLayout todofields = new HorizontalLayout();
        VerticalLayout todoList = new VerticalLayout();
        HorizontalLayout subjects = new HorizontalLayout();
        todogrid.addThemeNames("no-border","no-row-borders","row-strips");
        GridMultiSelectionModel<Todo> selectionModel = (GridMultiSelectionModel<Todo>) todogrid
                .setSelectionMode(Grid.SelectionMode.MULTI);
        selectionModel.selectAll();


        //Layouts//



        //Fields//
        ComboBox<String> taskstatus = new ComboBox<>("TaskStatus:");
        taskstatus.setItems("Completed","OnProgress","Cancelled");
        TextField subject = new TextField();
        subject.setLabel("נושא:");
        TextField customerid = new TextField();
        customerid.setLabel("שם הלקוח:");
        DatePicker dudate = new DatePicker();
        dudate.setClearButtonVisible(true);
        dudate.setLabel("תאריך סיום:");
        //Binder//
        binder.forField(subject).bind(Todo::getSubject,Todo::setSubject);
        binder.forField(dudate).bind(Todo::getDudate,Todo::setDudate);
        binder.forField(taskstatus).bind(Todo::getTaskStatus,Todo::setTaskStatus);
        binder.forField(customerid).withConverter(new StringToLongConverter(""))
                .bind(Todo::getCustomerID,Todo::setCustomerID);
        //Binder//


        addButton.addClickShortcut(Key.ENTER);
        addButton.setThemeName("primary");


        //Fields//






        todofields.add(subject,customerid,dudate,taskstatus,addButton);
        todofields.setDefaultVerticalComponentAlignment(FlexComponent.Alignment.BASELINE);
        todoList.setDefaultHorizontalComponentAlignment(FlexComponent.Alignment.BASELINE);
        todofields.getElement().getStyle().set("margin-left","auto");
        getContent().add(todofields,subjects,todoList,todogrid);
        Direction.set(Direction.RTL);

    }

    private void saveTodo() {

        service.update(todo);
    }

    private void updateGrid() {
        List<Todo> todo = service.findAll();

        todogrid.setItems(todo);
    }

    private void onComponentEvent(ClickEvent<Button> e) {
        try {
            binder.writeBean(todo);
            System.out.println(todo.getCustomerID());
            System.out.println(todo.getTaskStatus());
            System.out.println(todo.getDudate());
            System.out.println(todo.getSubject());
            saveTodo();
            updateGrid();
            binder.readBean(new Todo());
            //   } catch (ValidationException ex) {
            //     ex.printStackTrace();
        } catch (ValidationException ex) {
            ex.printStackTrace();
        }
    }
}

Ответы [ 2 ]

1 голос
/ 04 октября 2019

Я считаю, что проблема в том, что аннотация маршрута не управляется Spring Boot. Поэтому любой @Autowired не будет работать. Вы пытались добавить аннотацию @SpringComponent (https://vaadin.com/api/vaadin-spring/12.0.6/com/vaadin/flow/spring/annotation/SpringComponent.html)?

0 голосов
/ 04 октября 2019

Ваш сервис, вероятно, находится в пакете, который не сканируется весной, поэтому Spring не знает ни одного боба для инъекций и не находит его. Что вам нужно сделать, это сообщить Spring, где искать компоненты, или переместить ваш Application класс на несколько пакетов вверх (он автоматически сканирует все пакеты, находящиеся ниже IIRC).

Вы можете определить, где spring должна искать spring-компоненты в аннотации @SpringBootApplication в вашем классе Application: предоставить список пакетов, в которых есть пружинные компоненты в атрибуте scanBasePackages.

Как только Spring узнает о вашем TodoService, он успешно внедрит его в ваше представление.

Редактировать: SQL-запрос для TodoService::findAll также кажется странным, вы выбираете столбцыID, TaskStatus, dudate, subject но из набора результатов вы читаете значения ID, UserID, descriptionID, taskstatus. Это не то, что вызвало вашу текущую ошибку, но приведет к другой ошибке, как только вы исправите свою текущую.

...