Spring MVC Hibernate Error java.lang.Object;无法转换为model.Employee

时间:2016-02-09 04:12:25

标签: java spring hibernate spring-mvc

我正在尝试将hibernate与Spring集成。这是代码,

Employee.java

package java4s.model;

import java.util.Date;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.web.servlet.ModelAndView;

public class Employee {

    @NotEmpty
    private String userid;

    @Size(min = 3, max = 20)
    private String firstname;

    @Size(min = 3, max = 20)
    private String lastname;    

    @NotEmpty
    private String mobileno;

    @NotEmpty
    @Size(min = 3, max = 20)
    private String username;

    @NotEmpty
    @Size(min = 3, max = 20)
    private String password;

    @NotEmpty
    @Pattern(regexp = ".+@.+\\.[a-z]+")
    private String email;

    @NotNull
    @NotEmpty
    private String birthDate;

    @NotEmpty
    private String profession;
    private String studenterrors;   

    public String getUserid()
    {
        return userid;
    }
    public void setUserid(String userid)
    {
        this.userid = userid;
    }

    public String getUsername()
    {
        return username;
    }
    public void setUsername(String username)
    {
        this.username = username;
    }
    public String getFirstname()
    {
        return firstname;
    }
    public void setFirstname(String firstname)
    {
        this.firstname = firstname;
    }
    public String getLastname()
    {
        return lastname;
    }
    public void setLastname(String lastname)
    {
        this.lastname = lastname;
    }
    public String getMobileno()
    {
        return mobileno;
    }
    public void setMobileno(String mobileno)
    {
        this.mobileno = mobileno;
    }

    public String getPassword()
    {
        return password;
    }
    public void setPassword(String password)
    {
        this.password = password;
    }
    public String getEmail()
    {
        return email;
    }
    public void setEmail(String email)
    {
        this.email = email;
    }
    public String getBirthdate()
    {
        return birthDate;
    }
    public void setBirthdate(String birthDate)
    {
        this.birthDate = birthDate;
    }
    public String getProfession()
    {
        return profession;
    }
    public void setProfession(String profession)
    {
        this.profession = profession;
    }
    public String getStudenterrors()
    {
        return studenterrors;
    }
    public void setStudenterrors(String studenterrors)
    {
        this.studenterrors = studenterrors;
    }
}

EmployeeServiceImpl.java

@SuppressWarnings("unchecked")
    @Override
    public List<Employee> getUserinfo(String username) {
        // TODO Auto-generated method stub

        Configuration configuration = new Configuration();
        configuration.configure();

        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        String sql_query = "SELECT username, firstname, lastname, emailid, profession, mobileno, to_char(birthdate, 'MM/DD/YYYY') AS birthdate, password FROM EmployeeInfo WHERE username = ?";
        Query query = session.createQuery(sql_query);
        query.setString(0, username);
        List<Employee> employees = (List<Employee>)query.list();

        return employees;
}

LoginController.java

@RequestMapping(value = "/edit", method=RequestMethod.GET)
public ModelAndView EditMyInfo(ModelMap model, @ModelAttribute("editForm") Employee employee, HttpSession session) {

List<Employee> user_info = emp_service.getUserinfo((String)session.getAttribute("session_username"));
List<String> professionList = new ArrayList();
professionList.add("Developer");
professionList.add("Designer");
professionList.add("IT Manager");
model.put("professionList", professionList);
employee.setUsername(user_info.get(0).getUsername().toString());
employee.setFirstname(user_info.get(0).getFirstname().toString());
employee.setLastname(user_info.get(0).getLastname().toString());
employee.setEmail(user_info.get(0).getEmail().toString());
employee.setMobileno(user_info.get(0).getMobileno().toString());
employee.setBirthdate(user_info.get(0).getBirthdate());
return new ModelAndView("edit",model);
}

edit.jsp文件

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<c:if test="${session_username != null }">Hello ${session_username}!</c:if>
    <font face="verdana" size="2">
        ${welcomeMessage} <BR><BR>
        <form:form action="${pageContext.request.contextPath}/editemployee" method="POST" modelAttribute="editForm">

            <table>
                <tr>
                    <td colspan="2" align="center">Spring MVC Form Demo - Edit</td>
                </tr>
                <tr>
                    <td>User Name</td>
                    <td><form:input path="username" /></td>
                </tr>
                <tr>
                    <td>First Name</td>
                    <td><form:input path="firstname" /></td>
                </tr>
                <tr>
                    <td>Last Name</td>
                    <td><form:input path="lastname" /></td>
                </tr>
                <tr>
                    <td>Mobile No.</td>
                    <td><form:input path="mobileno" /></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><form:password path="password" /></td>
                </tr>
                <tr>
                    <td>Email</td>
                    <td><form:input path="email" /></td>
                </tr>
                <tr>
                    <td>BirthDate (mm/dd/yyyy)</td>
                    <td><form:input path="birthdate" /></td>
                </tr>
                <tr>
                    <td>Profession</td>
                    <td><form:select path="profession" items="${professionList}" /></td>
                </tr>
                <tr>
                    <td colspan="2" align="center"><input type="submit" value="Submit" /></td>
                </tr>                                   
            </table>                                        
        </form:form>
    </font> 
</body>
</html>

错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java4s.model.Employee
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

root cause

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java4s.model.Employee
    java4s.controller.LoginSuccessController.EditMyInfo(LoginSuccessController.java:106)
    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:606)
    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:967)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

我发现错误在

employee.setUsername(user_info.get(0).getUsername().toString());
employee.setFirstname(user_info.get(0).getFirstname().toString());
employee.setLastname(user_info.get(0).getLastname().toString());
employee.setEmail(user_info.get(0).getEmail().toString());
employee.setMobileno(user_info.get(0).getMobileno().toString());
employee.setBirthdate(user_info.get(0).getBirthdate());

如何解决此错误?

1 个答案:

答案 0 :(得分:1)

您的代码中存在一些问题

您需要向@Table添加Employ@Id注释     正如@KonstantinPavlov建议的那样。

您需要userid上的String sql_query = "SELECT username, firstname, lastname, emailid, profession, mobileno, to_char(birthdate, 'MM/DD/YYYY') AS birthdate, password FROM EmployeeInfo WHERE username = ?"; Query query = session.createQuery(sql_query); query.setString(0, username); List<Employee> employees = (List<Employee>)query.list(); 注释。

此代码不正确

Employee

您需要FROM EmployeeInfo,但使用Employee。 Hibernate无法将您的投影转换为new(它需要一个变换器或String hqlQuery = "FROM Employee WHERE username = :userName"; Query query = session.createQuery(hqlQuery); query.setParameter("userName", username); List<Employee> employees = (List<Employee>)query.list(); 运算符,并在查询中使用构造函数)。您的查询看起来像SQL,但您需要HQL。

SessionFactory

您不需要为每个请求构建LocalSessionFactoryBean!您需要使用Spring reloadRowsAtIndexPath创建它。

您打开会话但不关闭它。

您开始一个事务但不提交或回滚它。