Я пытаюсь вставить данные формы в базу данных Mysql, используя модель с использованием hibernate.
Детали приложения: Я пытаюсь вставить Репетитора (лекцию / Учителя) в Базу данных;У репетитора есть Имя, электронная почта, img, специальность и степень. Все они являются строковыми, кроме img is longblob
Я создал мою модель, сопоставил ее с полем базы данных и создал JSPform. Всякий раз, когда я нажимаю "Отправить", возникает исключение ... Ниже приведена подробная информация о моей проблеме, пожалуйста, сообщите мне в комментариях, если потребуется какая-либо дополнительная информация.Спасибо за ваше время.
Вот моя модель.
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
Iпри отправке формы получаю следующее исключение ...
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 Config
<!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>