2016-05-13 72 views
0

我想跟隨一個教程來使用PostgreSQL作爲數據庫與Hibernate,Tomcat作爲服務器和Eclipse作爲IDE的簡單的Web應用程序。簡單的Web應用程序使用PostgreSQL和Tomcat

的用戶需要輸入名字,姓氏和國家到一個簡單的形式

<!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> 

然後,我有AddUser.java作爲控制器模型視圖控制器模式

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); 
    } 

} 

而且User.java爲模型

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; 
    } 
} 

最後,useradd.jsp作爲視圖和應該顯示寫入數據庫的數據。

<%@ 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> 

我也在/ src文件夾中所做的hibernate.cfg.xml文件

<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> 

我可以在姓/名/國家運行應用程序,類型,但是,當我按下create,它會顯示以下錯誤:HTTP狀態500 - 未知實體:model.User

當然,它不會向DB寫入任何內容。

這是控制檯顯示:

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 : [email protected] 
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) 

我一直停留了幾個小時,也找不到任何解決辦法。

希望你們能幫助我。提前致謝!

+0

你是如何打包和部署應用程序? 'model/User.class'在哪裏? –

回答

2

如果使用Hiberanate 5,請用這種方式創建會話工廠:中

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 

代替

 Configuration config = new Configuration().configure(); 
    ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build(); 
    SessionFactory factory = config.buildSessionFactory(servReg); 
+0

它的工作! 非常感謝! 所以這個問題與Hibernate版本有關?事實上,正如你所說,我正在使用5.1最終版本 – NoobNe0

相關問題