简体   繁体   English

SpringMvc + Hibernate:在手动向表中插入数据时出现NullPointerException

[英]SpringMvc+Hibernate: Getting NullPointerException in manually inserting data to table

I am getting this error when i am trying to insert manually to MySql table with hibernate. 当我尝试使用休眠方式手动插入MySql表时,出现此错误。 I am trying to insert some default data to my application but while inserting manually i am getting Null pointer exception. 我正在尝试向应用程序中插入一些默认数据,但是在手动插入时却出现了Null指针异常。 I am new in java programming so can't able to understand how to fix this error. 我是Java编程的新手,因此无法理解如何解决此错误。 If anyone can help me with this would me really appreciated.. 如果有人可以帮助我,我将非常感激。

User_Role Class : User_Role类别:

package com.sanjay31321.sys.model;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity @Table(name="user_role")
public class User_Role {

    @Id @Column @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    @Column(name="role_name")
    private String name;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

InsertUserRole InsertUserRole

import org.springframework.beans.factory.annotation.Autowired;

import com.sanjay31321.sys.model.User_Role;
import com.sanjay31321.sys.service.UserRoleService;

public class InsertUserRole {
    private static final Logger logger = LoggerFactory.getLogger(InsertUserRole.class);

    @Autowired
    private UserRoleService userRoleService;

    public void insert() {
        User_Role role = new User_Role();

        role.setId(1);
        role.setName("ROLE_ADMIN");
        logger.info("id : "+ role.getId() + " | Role : " + role.getName());
        userRoleService.addUserRole(role);
    }
}

Error: 错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause

java.lang.NullPointerException com.sanjay31321.sys.preset.data.InsertUserRole.insert(InsertUserRole.java:22) com.sanjay31321.sys.preset.DefaultDataInstall.install(DefaultDataInstall.java:23) com.sanjay31321.sys.controller.DefaultDataController.postinstall(DefaultDataController.java:31) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855) javax.servlet.http.HttpServlet.service(HttpServlet.java:641) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829) javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

DefaultDataController class

package com.sanjay31321.sys.controller;

import java.util.Locale;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sanjay31321.sys.preset.DefaultDataInstall;
import com.sanjay31321.sys.preset.model.Install;

@Controller
public class DefaultDataController {
    private static final Logger logger = LoggerFactory.getLogger(DefaultDataController.class);

    @RequestMapping(value = "/install", method = RequestMethod.GET)
    public String getinstall(Locale locale, Install install) {
        logger.info("Welcome to Install Default Settings page ! GET METHOD : The client locale is {}.", locale);
        return "install";
    }

    @RequestMapping(value="/install", method=RequestMethod.POST)
    public String postinstall(@Valid  Install install, BindingResult result, Locale locale){
        logger.info("Welcome to Install Default Settings page ! POST METHOD : The client locale is {}.", locale);
        DefaultDataInstall settings = new DefaultDataInstall();
        settings.install();
        return "install";
    }
}

DefaultDataInstall class

package com.sanjay31321.sys.preset; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sanjay31321.sys.preset.data.InsertCourse; import com.sanjay31321.sys.preset.data.InsertFeedback; import com.sanjay31321.sys.preset.data.InsertQuestion; import com.sanjay31321.sys.preset.data.InsertQuestionSet; import com.sanjay31321.sys.preset.data.InsertStudent; import com.sanjay31321.sys.preset.data.InsertSubject; import com.sanjay31321.sys.preset.data.InsertTeacher; import com.sanjay31321.sys.preset.data.InsertUser; import com.sanjay31321.sys.preset.data.InsertUserRole; public class DefaultDataInstall { private static final Logger logger = LoggerFactory.getLogger(DefaultDataInstall.class); public void install() { InsertUserRole role = new InsertUserRole(); role.insert(); logger.info("User Role data is installed"); } }

I have attached the classes you asked. 我已附上您要求的课程。

I saw you code on github. 我在github上看到了您的代码。

It is showing that error because userRoleService in InsertUserRole is null. 它显示该错误,因为userRoleService中的InsertUserRole为null。 so you can not call any method on it. 因此您不能在其上调用任何方法。

Why? 为什么?

You creating InsertUserRole object using new keyword in DefaultDataInstall . 您使用DefaultDataInstall new关键字创建InsertUserRole对象。 @Autowired don't work when you do that it only works when DefaultDataInstall is also instantiated by spring. @Autowired在您执行此操作时不起作用,它仅在Spring也实例化DefaultDataInstall时才起作用。 Spring can only inject something in an object only if it is creating it. Spring只能在创建对象时将其注入对象。

How to fix it. 如何解决。

Instantiate all the objects inside the preset package ie mark them as @Component . 实例化preset包中的所有对象, @Component它们标记为@Component

Other way is that You inject ApplicationContext in the controller and pass it to the objects you are creating and get the services from the AppContext. 另一种方法是,您在控制器中注入ApplicationContext并将其传递给正在创建的对象,并从AppContext获取服务。

@Controller
public class DefaultDataController {
    private static final Logger logger = LoggerFactory.getLogger(DefaultDataController.class);

    @Autowired private ApplicationContext applicationContext;   

    @RequestMapping(value="/install", method=RequestMethod.POST)
    public String postinstall(@Valid  Install install, BindingResult result, Locale locale){
        logger.info("Welcome to Install Default Settings page ! POST METHOD : The client locale is {}.", locale);       
        DefaultDataInstall settings = new DefaultDataInstall(applicationContext);//create a constructor which acceps ApplicationContext object
        settings.install();
        return "install";
    }

    //other code
}

Pass the ApplicationContext object to all the order objects where you want to use spring beans. ApplicationContext对象传递到要使用Spring bean的所有订单对象。

public class DefaultDataInstall {

    private static final Logger logger = LoggerFactory.getLogger(DefaultDataInstall.class);
    private ApplicationContext applicationContext;

    public DefaultDataInstall(ApplicationContext applicationContext){
        this.applicationContext = applicationContext;
    }

    public void install() {

        InsertUserRole role = new InsertUserRole();
        role.setUserRoleService(applicationContext.getBean("userRoleServiceImpl"));
        role.insert();
        logger.info("User Role data is installed");

        //other stuff
    }
}

Now you can use the passed service to call methods on them 现在,您可以使用传递的服务来调用它们上的方法

public class InsertUserRole {
    private static final Logger logger = LoggerFactory.getLogger(InsertUserRole.class);

    private UserRoleService userRoleService;

    public void setUserRoleService(UserRoleService){
        this.userRoleService = userRoleService;
    }

    //other code
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM