Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带hibernate注释的Spring MVC一对一CRUD_Spring_Hibernate_Spring Mvc - Fatal编程技术网

带hibernate注释的Spring MVC一对一CRUD

带hibernate注释的Spring MVC一对一CRUD,spring,hibernate,spring-mvc,Spring,Hibernate,Spring Mvc,我不熟悉Spring和hibernate框架。我需要使用SpringMVC和hibernate插入员工详细信息。我需要从resightrationemployee.jsp获取员工和地址的详细信息,并需要使用Bean类保存到数据库中。但当我从Employee bean中获取地址时,会出现空指针异常。我还怀疑我需要使用哪个Bean来插入数据。我的方法如下 AppController.java @Controller @RequestMapping("/") @SessionAttributes("r

我不熟悉Spring和hibernate框架。我需要使用SpringMVC和hibernate插入员工详细信息。我需要从resightrationemployee.jsp获取员工和地址的详细信息,并需要使用Bean类保存到数据库中。但当我从Employee bean中获取地址时,会出现空指针异常。我还怀疑我需要使用哪个Bean来插入数据。我的方法如下

AppController.java

@Controller
@RequestMapping("/")
@SessionAttributes("roles")
public class AppController {

@Autowired
UserService userService;

@Autowired
EmployeeService employeeService;

@Autowired
UserProfileService userProfileService;

@Autowired
MessageSource messageSource;

@Autowired
PersistentTokenBasedRememberMeServices persistentTokenBasedRememberMeServices;

@Autowired
AuthenticationTrustResolver authenticationTrustResolver;
/*@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String listUsers(ModelMap model) {

    List<User> users = userService.findAllUsers();
    model.addAttribute("users", users);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userslist";
}*/
@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String listUsers(ModelMap model) {

    List<User> users = userService.findAllUsers();
    List<Employee> employees=employeeService.findAllEmployees();
    model.addAttribute("users", users);
    model.addAttribute("employees", employees);
    model.addAttribute("loggedinuser", getPrincipal());
    return "home";
}

@RequestMapping(value = { "/newuser" }, method = RequestMethod.GET)
public String newUser(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("edit", false);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registration";
}

@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST)
public String saveUser(@Valid User user, BindingResult result,
        ModelMap model) {

    if (result.hasErrors()) {
        return "registration";
    }

    if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){
        FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault()));
        result.addError(ssoError);
        return "registration";
    }

    userService.saveUser(user);

    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " registered successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/newemployee" }, method = RequestMethod.GET)
public String addEmployee(ModelMap model) {
    Employee employee = new Employee();
    model.addAttribute("employee", employee);
    model.addAttribute("edit", false);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationemployee";
}

@RequestMapping(value = { "/newemployee" }, method = RequestMethod.POST)
public String saveEmployee(@Valid Employee employee, BindingResult result,
        ModelMap model) {
    System.out.println("Employee name:"+employee.getEmployeeReferenceId());
    System.out.println("Address of Employee is:"+employee.getAddress().getPlace());
    if (result.hasErrors()) {
        return "registrationemployee";
    }

    if(!employeeService.isEmployeeReferenceIdUnique(employee.getEmployeeId(), employee.getEmployeeReferenceId())){
        FieldError referenceIdError =new FieldError("employee","employeeReferenceId",messageSource.getMessage("non.unique.employeeReferenceId", new String[]{employee.getEmployeeReferenceId()}, Locale.getDefault()));
        result.addError(referenceIdError);
        return "registrationemployee";
    }

    employeeService.saveEmployee(employee);

    model.addAttribute("success", "Employee " + employee.getEmployeeName() + " registered successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.GET)
public String editUser(@PathVariable String ssoId, ModelMap model) {
    User user = userService.findBySSO(ssoId);
    model.addAttribute("user", user);
    model.addAttribute("edit", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registration";
}
@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.POST)
public String updateUser(@Valid User user, BindingResult result,
        ModelMap model, @PathVariable String ssoId) {

    if (result.hasErrors()) {
        return "registration";
    }

    userService.updateUser(user);

    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " updated successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/delete-user-{ssoId}" }, method = RequestMethod.GET)
public String deleteUser(@PathVariable String ssoId) {
    userService.deleteUserBySSO(ssoId);
    return "redirect:/list";
}

@ModelAttribute("roles")
public List<UserProfile> initializeProfiles() {
    return userProfileService.findAll();
}

@RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) {
    model.addAttribute("loggedinuser", getPrincipal());
    return "accessDenied";
}

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage() {
    if (isCurrentAuthenticationAnonymous()) {
        return "login";
    } else {
        return "redirect:/list";  
    }
}

@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response){
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){    
        persistentTokenBasedRememberMeServices.logout(request, response, auth);
        SecurityContextHolder.getContext().setAuthentication(null);
    }
    return "redirect:/login?logout";
}
private String getPrincipal(){
    String userName = null;
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    if (principal instanceof UserDetails) {
        userName = ((UserDetails)principal).getUsername();
    } else {
        userName = principal.toString();
    }
    return userName;
}

private boolean isCurrentAuthenticationAnonymous() {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return authenticationTrustResolver.isAnonymous(authentication);
}
}
Address.java

@Entity
@Table(name="address")

public class Address implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;


@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="employee_address_id")
private int employeeAddressId=0;

public void setEmployeeAddressId(int employeeAddressId) {
    this.employeeAddressId = employeeAddressId;
}



@Column(name="address",length=255)
private String place=null;


@OneToOne(targetEntity=Employee.class,fetch=FetchType.EAGER , cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name="employee_id",referencedColumnName="employee_id")
private Employee parent;


public String getPlace() {
    return place;
}

public void setPlace(String place) {
    this.place = place;
}

public Employee getParent() {
    return parent;
}

public void setParent(Employee parent) {
    this.parent = parent;
}

public int getEmployeeAddressId() {
    return employeeAddressId;
}

}
EmployeeService.java

public interface EmployeeService {

Employee findById(int id);
Employee findByReferenceId(String employeeRefernceId);
void saveEmployee(Employee employee);
void updateEmployee(Employee employee);
void deleteEmployeeByReferenceId(String employeeRefernceId);
List<Employee> findAllEmployees(); 
boolean isEmployeeReferenceIdUnique(Integer id, String employeeRefernceId);
}

我真的觉得我在这件事上错过了什么。纠正我的错误

您需要检查如何在jsp表单中绑定员工模型

示例代码应如下所示:-

<form:form action="${pageContext.request.contextPath}/register"
                   method="post" commandName="employee">

         <div>
            <label for="name">Name</label>
            <form:errors path="employeeName" cssStyle="color: #ff0000" />
            <form:input path="employeeName" id="employeeName" class="form-Control"  />
        </div>
        <div>
            <label for="address.placeName">Street Name</label>
            <form:input path="address.placeName" id="placeName" class="form-Control" />
        </div>
</form:form>

名称
街道名称

希望这能解决您的问题。

回答以下问题:-

这就是我的地址表没有值。但是员工的详细信息被记录下来了 插入。我是否应该保留address对象而不是Employee 对象来实现这一点(通过关系映射)

对于两个表上的数据持久化,您需要使用双向关系映射,示例如下:-

<form:form action="${pageContext.request.contextPath}/register"
                   method="post" commandName="employee">

         <div>
            <label for="name">Name</label>
            <form:errors path="employeeName" cssStyle="color: #ff0000" />
            <form:input path="employeeName" id="employeeName" class="form-Control"  />
        </div>
        <div>
            <label for="address.placeName">Street Name</label>
            <form:input path="address.placeName" id="placeName" class="form-Control" />
        </div>
</form:form>
雇员阶级

   @OneToOne
    @JoinColumn(name = "addressId")
    private Address address;
//getter setter
地址类

    @OneToOne
    private Customer customer;
//getter setter

然后在您的控制器中,您可以调用服务instant以仅持久化员工数据,然后当员工数据持久化时,地址数据也持久化。

What's on line(AppController.java:118)?只需先初始化place Kowalski的值即可。System.out.println(“员工地址为:”+Employee.getAddress().getPlace());这就是我所缺少的。您的员工地址似乎为空。。你应该填在Yes Kowalski里。我不知道如何填写这个值。这是一个POST请求。。客户端必须组装该对象..谢谢soewin。这对我有用。但还有一个问题。这就是我的地址表没有值。但是员工的详细信息被插入了。我是否应该保留address对象而不是Employee对象来实现这一点(通过关系映射)
        SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/SpringMVCWithSpringSecurity] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
    java.lang.NullPointerException
    at com.sprongmvc.controller.AppController.saveEmployee(AppController.java:118)
    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)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
    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:968)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:870)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:157)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:120)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    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)
    at java.lang.Thread.run(Unknown Source)
<form:form action="${pageContext.request.contextPath}/register"
                   method="post" commandName="employee">

         <div>
            <label for="name">Name</label>
            <form:errors path="employeeName" cssStyle="color: #ff0000" />
            <form:input path="employeeName" id="employeeName" class="form-Control"  />
        </div>
        <div>
            <label for="address.placeName">Street Name</label>
            <form:input path="address.placeName" id="placeName" class="form-Control" />
        </div>
</form:form>
   @OneToOne
    @JoinColumn(name = "addressId")
    private Address address;
//getter setter
    @OneToOne
    private Customer customer;
//getter setter