Issue
I'm trying to follow a tutorial to make a simple web application using PostgreSQL as db with Hibernate, Tomcat as server and Eclipse as IDE.
The user should enter name, surname and country to a simple form
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>My first Web App</title>
</head>
<body>
<h1>Let's create a new user</h1>
<form method="POST" action = "CreateUser.do">
First Name <input type = "text" size = "40" maxlength = "40" name = "firstname" /><br/>
Last Name <input type = "text" size = "40" maxlength = "40" name = "lastname" /><br/>
Country <input type = "text" size = "40" maxlength = "40" name = "country" /><br/>
<input type = "submit" value = "create" >
</form>
</body>
</html>
Then I have AddUser.java as Controller in the Model View Controller pattern
package controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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 model.User;
/**
* Servlet implementation class AddUser
*/
@WebServlet(description = "Create new user Servlet", urlPatterns = {"/CreateUser.do"})
public class AddUser extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
RequestDispatcher view = request.getRequestDispatcher("useradd.jsp");
view.forward(request, response);
*/
Configuration config = new Configuration().configure();
ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory factory = config.buildSessionFactory(servReg);
Session session = factory.openSession();
session.beginTransaction();
User u = new User(request.getParameter("firstname"),
request.getParameter("lastname"),
request.getParameter("country"));
session.save(u);
session.getTransaction().commit();
session.close();
RequestDispatcher view = request.getRequestDispatcher("useradd.jsp");
view.forward(request, response);
}
}
And User.java as Model
package model;
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 {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_id", nullable=false, unique=true)
private int id;
@Column(name="firstname", length=40, nullable=false)
private String firstname;
@Column(name="lastname", length=40, nullable=false)
private String lastname;
@Column(name="country", length=40, nullable=true)
private String country;
public User(String firstName, String lastName, String country) {
firstname = firstName;
lastname = lastName;
this.country = country;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Lastly, useradd.jsp acts as view and should show the data written in the DB.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>My first Web App - New User Created!</title>
</head>
<body>
<h1>New User Created</h1>
<p>
First Name: <% String fName = request.getParameter("firstname"); out.print(fName); %> <br/>
Last Name: <% String lName = request.getParameter("lastname"); out.print(lName); %> <br/>
Country: <% String country = request.getParameter("country"); out.print(country); %> <br/>
</p>
</body>
</html>
I've also made the hibernate.cfg.xml file in the /src folder
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/firstapp</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">admin</property>
<property name="show_sql">false</property>
<mapping class="model.User"/>
</session-factory>
</hibernate-configuration>
I can run the application, type in first name/last name/country but, when I press create, it shows this error: HTTP Status 500 - Unknown entity: model.User
Of course it doesn't write anything to the DB.
This is what the console shows:
mag 13, 2016 7:20:44 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
AVVERTENZA: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:2 - Hibernate' did not find a matching property.
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Server version: Apache Tomcat/8.0.33
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Server built: Mar 18 2016 20:31:49 UTC
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Server number: 8.0.33.0
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: OS Name: Windows 10
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: OS Version: 10.0
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Architecture: x86
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Java Home: C:\Program Files (x86)\Java\jre1.8.0_91
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: JVM Version: 1.8.0_91-b14
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: JVM Vendor: Oracle Corporation
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: CATALINA_BASE: C:\Users\Antonio\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: CATALINA_HOME: C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.0
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Dcatalina.base=C:\Users\Antonio\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Dcatalina.home=C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.0
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Dwtp.deploy=C:\Users\Antonio\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Djava.endorsed.dirs=C:\Program Files (x86)\Apache Software Foundation\Tomcat 8.0\endorsed
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.VersionLoggerListener log
INFORMAZIONI: Command line argument: -Dfile.encoding=Cp1252
mag 13, 2016 7:20:44 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFORMAZIONI: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files (x86)\Java\jre1.8.0_91\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files (x86)/Java/jre1.8.0_91/bin/client;C:/Program Files (x86)/Java/jre1.8.0_91/bin;C:/Program Files (x86)/Java/jre1.8.0_91/lib/i386;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Users\Antonio\Desktop\eclipse;;.
mag 13, 2016 7:20:44 PM org.apache.coyote.AbstractProtocol init
INFORMAZIONI: Initializing ProtocolHandler ["http-nio-8080"]
mag 13, 2016 7:20:44 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFORMAZIONI: Using a shared selector for servlet write/read
mag 13, 2016 7:20:44 PM org.apache.coyote.AbstractProtocol init
INFORMAZIONI: Initializing ProtocolHandler ["ajp-nio-8009"]
mag 13, 2016 7:20:44 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFORMAZIONI: Using a shared selector for servlet write/read
mag 13, 2016 7:20:44 PM org.apache.catalina.startup.Catalina load
INFORMAZIONI: Initialization processed in 1448 ms
mag 13, 2016 7:20:44 PM org.apache.catalina.core.StandardService startInternal
INFORMAZIONI: Starting service Catalina
mag 13, 2016 7:20:44 PM org.apache.catalina.core.StandardEngine startInternal
INFORMAZIONI: Starting Servlet Engine: Apache Tomcat/8.0.33
mag 13, 2016 7:20:45 PM org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
INFORMAZIONI: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [199] milliseconds.
mag 13, 2016 7:20:46 PM org.apache.jasper.servlet.TldScanner scanJars
INFORMAZIONI: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
mag 13, 2016 7:20:46 PM org.apache.coyote.AbstractProtocol start
INFORMAZIONI: Starting ProtocolHandler ["http-nio-8080"]
mag 13, 2016 7:20:46 PM org.apache.coyote.AbstractProtocol start
INFORMAZIONI: Starting ProtocolHandler ["ajp-nio-8009"]
mag 13, 2016 7:20:46 PM org.apache.catalina.startup.Catalina start
INFORMAZIONI: Server startup in 1935 ms
mag 13, 2016 7:21:06 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
mag 13, 2016 7:21:06 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
mag 13, 2016 7:21:06 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
mag 13, 2016 7:21:07 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
mag 13, 2016 7:21:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
mag 13, 2016 7:21:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/firstapp]
mag 13, 2016 7:21:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
mag 13, 2016 7:21:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
mag 13, 2016 7:21:08 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
mag 13, 2016 7:21:08 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
mag 13, 2016 7:21:09 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
mag 13, 2016 7:21:09 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@bfbdad
mag 13, 2016 7:21:10 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [controller.AddUser] in context with path [/2_-_Hibernate] threw exception
org.hibernate.MappingException: Unknown entity: model.User
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1533)
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:682)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
at controller.AddUser.doPost(AddUser.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
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.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:1502)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
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)
I've been stuck for hours and cannot find any solution.
Hope you guys can help me. Thanks in advance!
Solution
If you are using Hiberanate 5, please create Session factory in this way:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
instead of
Configuration config = new Configuration().configure();
ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory factory = config.buildSessionFactory(servReg);
Answered By - shankarsh15
Answer Checked By - David Goodson (JavaFixing Volunteer)