一尘不染

请求处理失败;嵌套的异常是org.hibernate.MappingException:未知实体

spring-mvc

我正在尝试使用Hibernate模型将表单数据插入Mysql数据库。

应用程序详细信息: 我正在尝试在数据库中插入一个教师(讲师/老师);老师的姓名,电子邮件,img,专业和程度均为字符串,除了 img
longblob

我创建了我的模型,映射了数据库字段并创建了JSP表单。每当我点击Submit时,都会有一个异常…以下是我的问题的详细信息,如果需要任何其他信息,请在评论中告知我。感谢您的时间。

这是我的模特。

Tutor.java(模型)

package com.suvrat;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotBlank;

import com.mysql.jdbc.Blob;
@Entity
@Table(name ="tutor")
public class Tutor {


    public Tutor() {

    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "tutor_id", updatable = false, nullable = false)
    public int tutor_id;

    @Column(name = "tutor_name")
    @NotBlank(message="Required")
    @NotNull(message="Required")
    public String tutor_name;

    @Column(name = "tutor_email")
    @NotBlank(message="Required")
    @NotNull(message="Required")
    public String tutor_email;

    @Column(name = "img")
    public byte[] img;

    @Column(name = "speciality")
    @NotBlank(message="Required")
    @NotNull(message="Required")
    public String speciality;

    @Column(name = "phone_number")
    @NotBlank(message="Required")
    @NotNull(message="Required")
    public String phone_number;

    @Column(name = "degree")
    @NotBlank(message="Required")
    @NotNull(message="Required")
    public String degree;

    public int getTutor_id() {
        return tutor_id;
    }

    public void setTutor_id(int tutor_id) {
        this.tutor_id = tutor_id;
    }

    public String getTutor_name() {
        return tutor_name;
    }

    public void setTutor_name(String tutor_name) {
        this.tutor_name = tutor_name;
    }

    public String getTutor_email() {
        return tutor_email;
    }

    public void setTutor_email(String tutor_email) {
        this.tutor_email = tutor_email;
    }

    public byte[] getImg() {
        return img;
    }

    public void setImg(byte[] img) {
        this.img = img;
    }

    public String getSpeciality() {
        return speciality;
    }

    public void setSpeciality(String speciality) {
        this.speciality = speciality;
    }

    public String getPhone_number() {
        return phone_number;
    }

    public void setPhone_number(String phone_number) {
        this.phone_number = phone_number;
    }

    public String getDegree() {
        return degree;
    }

    public void setDegree(String degree) {
        this.degree = degree;
    }



}

控制器类

package com.suvrat;

import javax.validation.Valid;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
public class HandleTutor {

    @RequestMapping("/insertTutor")
    public String insertBegin(Model m) {
        m.addAttribute("tutor", new Tutor());
        return "insertTutor";
    }

    @RequestMapping(value = "/ProcessTutorRegistration",method = RequestMethod.POST)
    public String ProcessUserRegistration(@RequestParam("fileUpload") CommonsMultipartFile fileUpload,
            @Valid @ModelAttribute("tutor") Tutor tutor, BindingResult theBindingResult) {
        if (theBindingResult.hasErrors()) {
            return "insertTutor";
        } else {
            SessionFactory factory = new Configuration().configure("/resources/hibernate.cfg.xml")
                    .addAnnotatedClass(User.class).buildSessionFactory();

            Session session = factory.getCurrentSession();

            try {

                if (fileUpload != null) {


                        System.out.println("Saving file: " + fileUpload.getOriginalFilename());

                        tutor.setImg(fileUpload.getBytes());
                        System.out.println("**********In IF********");

                }

                System.out.println("Transaction");
                session.beginTransaction();
                session.save(tutor);
                session.getTransaction().commit();
                System.out.println("Done!");
            } finally {
                factory.close();
            }
            return "user-confirm";
        }

    }
}

和JSP页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style type="text/css">
.error {
    color: red;
}
</style>

</head>
<body>
    <center>
        <h1>Insert Tutor!</h1>
        <form:form method="post" action="ProcessTutorRegistration" modelAttribute="tutor" enctype="multipart/form-data">

    Tutor Name <form:input path="tutor_name" />
            <form:errors path="tutor_name" cssClass="error" />
            <br>
            <br>
    Email  <form:input path="tutor_email" />
            <form:errors path="tutor_email" cssClass="error" />
            <br>
            <br>
    Image <input name="fileUpload" type="file" size="50" />
            <form:errors path="img" cssClass="error" />
            <br>
            <br>
    Speciality <form:input path="speciality" />
            <form:errors path="speciality" cssClass="error" />
            <br>
            <br>
    Phone Number <form:input  path="phone_number" />
            <form:errors path="phone_number" cssClass="error" />
            <br>
            <br>
    Degree <form:input  path="degree" />
            <form:errors path="degree" cssClass="error" />
            <br>
            <br>

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

    </center>
</body>
</html>

数据库架构

tutor_id    1       NO  int 10  0   
tutor_name  2       NO  varchar         
tutor_email 3       NO  varchar         
img         4       NO  longblob            
speciality  5       NO  varchar         
phone_number6       NO  varchar         
degree      7       NO  varchar

提交表格时,我收到以下例外情况…

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/Imperio] threw exception [Request processing failed; nested exception is org.hibernate.MappingException: Unknown entity: com.suvrat.Tutor] with root cause
org.hibernate.MappingException: Unknown entity: com.suvrat.Tutor
    at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:618)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1595)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:667)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:659)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:654)
    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.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:338)
    at com.sun.proxy.$Proxy50.save(Unknown Source)
    at com.suvrat.HandleTutor.ProcessUserRegistration(HandleTutor.java:51)
    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:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    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:966)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

hibernate配置

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/tutorsystem?useSSL=false</property>
        <property name="connection.username">xxxx</property>
        <property name="connection.password">xxxx</property>

        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="connection.pool_size">1</property>

        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Echo the SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Set the current session context -->
        <property name="current_session_context_class">thread</property>

    </session-factory>

</hibernate-configuration>

Web XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">


    <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


</web-app>

阅读 249

收藏
2020-06-01

共1个答案

一尘不染

sessionFactory定义中,您可以定义模型位于哪些包中。将此属性添加到您的<session-factory>

<property name="packagesToScan" value="com.suvrat"/>

或者,您可以将此类显式添加到Java中的SessionFactory定义中:

SessionFactory factory = new Configuration().configure("/resources/hibernate.cfg.xml")
                .addAnnotatedClass(Tutor.class)
                .addAnnotatedClass(User.class)
                .buildSessionFactory();

在大多数情况下,您将使用包裹扫描方式。

评论

因为您使用的是Spring,所以建议将SessionFactory提取到另一个@Configuration,然后仅将其注入Controller中。您的应用程序应该只有一个SessionFactory。其次,在没有任何数据库访问的情况下,测试控制器要容易得多。

因此,像这样创建一个HibernateConfig:

@Configuration
public class HibernateConfig {
   @Bean
   public SessionFactory sessionFactory(){
     return  new Configuration().configure("/resources/hibernate.cfg.xml")
                    .addAnnotatedClass(Tutor.class)
                    .addAnnotatedClass(User.class)
                    .buildSessionFactory();
   }
}

然后像这样更改您的控制器:

@Controller
public class HandleTutor {  
   @Autowired
   private SessionFactory sessionFactory;
}
2020-06-01