我想使用Hibernate和Spring MVC在MySQL中实现简单的CRUD操作。我在Spring MVC中制作了一些Web应用程序,但是Hibernate对我来说还是一个新手。我试图在数据库中的一个表中创建一条记录,然后按照本教程进行操作:https://examples.javacodegeeks.com/enterprise-java/hibernate/hibernate-crud-operations-tutorial/但是,当我运行该应用程序时,它给出了org.hibernate.MappingException
我尝试了从文件hibernate-cfg.xml中保留和删除映射类行。我还检查了缺少的@Entity批注。
异常堆栈:
org.hibernate.MappingException: Unknown entity: com.eversoft.traverse.model.User
at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:704)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1731)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:118)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:176)
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:712)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:704)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:699)
at com.eversoft.traverse.daoimpl.UserDaoImpl.createUser(UserDaoImpl.java:43)
at com.eversoft.traverse.serviceimpl.UserServiceImpl.createUser(UserServiceImpl.java:22)
at com.eversoft.traverse.controller.UserController.addUserDummy(UserController.java:31)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:835)
User.java
package com.eversoft.traverse.model;
import java.io.Serializable;
import java.util.Date;
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="users")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column(name="firstName")
private String firstName;
@Column(name="middleName")
private String middleName;
@Column(name="lastName")
private String lastName;
@Column(name="nationality")
private String nationality;
@Column(name="dateOfBirth")
public Date dateOfBirth;
@Column(name="visaId")
private int visaId;
public User() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public int getVisaId() {
return visaId;
}
public void setVisaId(int visaId) {
this.visaId = visaId;
}
}
UserController.java
package com.eversoft.traverse.controller;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.eversoft.traverse.model.User;
import com.eversoft.traverse.service.UserService;
@Controller
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value="/adddummyvalue", method = RequestMethod.GET)
public String addUserDummy(Model model) {
User dummyUser = new User();
dummyUser.setDateOfBirth(new Date());
dummyUser.setFirstName("Bikalpa");
dummyUser.setLastName("Dhakal");
dummyUser.setMiddleName("Raj");
dummyUser.setNationality("Nepalese");
dummyUser.setVisaId(22);
userService.createUser(dummyUser);
return "home";
}
}
UserDaoImpl.java
package com.eversoft.traverse.daoimpl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.springframework.stereotype.Repository;
import com.eversoft.traverse.dao.UserDao;
import com.eversoft.traverse.model.User;
@Repository
public class UserDaoImpl implements UserDao {
static Session sessionObj;
static SessionFactory sessionFactoryObj;
//public final static Logger logger = Logger.getLogger(DbOperations.class);
// This Method Is Used To Create The Hibernate's SessionFactory Object
private static SessionFactory buildSessionFactory() {
// Creating Configuration Instance & Passing Hibernate Configuration File
Configuration configObj = new Configuration();
configObj.configure("hibernate.cfg.xml");
// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();
// Creating Hibernate SessionFactory Instance
sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
return sessionFactoryObj;
}
@Override
public void createUser(User user) {
try {
// Getting Session Object From SessionFactory
sessionObj = buildSessionFactory().openSession();
// Getting Transaction Object From Session Object
sessionObj.beginTransaction();
sessionObj.save(user);
// Committing The Transactions To The Database
sessionObj.getTransaction().commit();
} catch(Exception sqlException) {
if(null != sessionObj.getTransaction()) {
sessionObj.getTransaction().rollback();
}
sqlException.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
}
}
}
UserServiceImpl.java
package com.eversoft.traverse.serviceimpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.eversoft.traverse.dao.UserDao;
import com.eversoft.traverse.model.User;
import com.eversoft.traverse.service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserDao userDao;
public UserServiceImpl() {
}
@Override
public void createUser(User user) {
userDao.createUser(user);
}
}
hibernate-cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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>
<!-- SQL Dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sys</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">helloworld</property>
<property name="show_sql">true</property>
<!-- Specifying Session Context -->
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
<!-- <mapping class="com.eversoft.traverse.model.User" /> -->
<!-- Mapping With Model Class Containing Annotations -->
<!-- <mapping class="com.jcg.hibernate.crud.operations.Student" /> -->
</session-factory>
</hibernate-configuration>
当我按下http://localhost:8080/traverse/adddummyvalue时,我希望有一条新记录插入到表中,但我却得到了MappingException。
答案 0 :(得分:0)
您需要更改代码,因为您引用的示例是Hibernate 4.3
,并且您正在使用Hibernate 5.x
。请参考here以获得解释。
根据休眠5.x docs
更改代码StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() .configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();
return metadata.getSessionFactoryBuilder().build();