0

我是hibernate的新手,我想在提交数据时在mysql中做hibernate注释和自动生成表。但是我有一些错误,比如sql语法。请帮我解决这个错误。我的所有代码都在下面..

我的 Jsp 文件

<html>
<head>
</head>
<body>
<form action="controller" method="post">
        Id : <input type="text" name="id"><br>
        First-Name : <input type="text" name="fName"><br>
        Last-Name : <input type="text" name="lName"><br>
         <input type="submit" value="submit">
    </form>
</body>
</html>

这是我的 Pojo 课程

package com.connection;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "csl_emp")
public class Employee {

    @Id
    private int id;
    private String firstName, lastName;

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

}

这是我的服务器

package com.connection;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class controller
 */
public class controller extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public controller() {
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("in the controller");

        String id = request.getParameter("id");
        String fname = request.getParameter("fName");
        String lname = request.getParameter("lName");

        System.out.println(id + fname + lname);

        Employee employee = new Employee();
        employee.setFirstName(fname);
        employee.setLastName(lname);
        employee.setId(Integer.parseInt(id));

        EmpDao dao = new EmpDao();

        dao.addData(employee);

        RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/success.jsp");
        requestDispatcher.forward(request, response);

    }

}

这是我的道课

package com.connection;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

public class EmpDao {

    public void addData(Employee employee) {
        Session session = new AnnotationConfiguration().configure().buildSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        session.saveOrUpdate(employee);
        transaction.commit();
        session.close();
    }
}

这是我的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javadb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="hbm2ddl.auto">true</property>
        <mapping class="com.connection.Employee"/> 
    </session-factory>
</hibernate-configuration>

我有这样的错误

Sep 12, 2013 11:49:25 AM org.apache.catalina.core.AprLifecycleListener init
INFO: 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\java\jdk1.6.0_43\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/java/jdk1.6.0_43/bin/../jre/bin/server;C:/Program Files/java/jdk1.6.0_43/bin/../jre/bin;C:/Program Files/java/jdk1.6.0_43/bin/../jre/lib/amd64;C:\Windows\System32;C:\Program Files\java\jdk1.6.0_43\bin;C:\Program Files\apache-ant-1.8.4\bin;C:\Program Files (x86)\MySQL\MySQL Server 5.0\bin;D:\eclipse;;.
Sep 12, 2013 11:49:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:jspcrud' did not find a matching property.
Sep 12, 2013 11:49:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Hibernate-J2EE-Annotation' did not find a matching property.
Sep 12, 2013 11:49:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Sep 12, 2013 11:49:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Sep 12, 2013 11:49:27 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2769 ms
Sep 12, 2013 11:49:27 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Sep 12, 2013 11:49:27 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.40
Sep 12, 2013 11:49:28 AM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [203] milliseconds.
Sep 12, 2013 11:49:30 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(E:\projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Hibernate-J2EE-Annotation\WEB-INF\lib\servlet-api-2.4.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
Sep 12, 2013 11:49:31 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Sep 12, 2013 11:49:31 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Sep 12, 2013 11:49:31 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3324 ms
in the controller
1chiragsoni
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Sep 12, 2013 11:49:48 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [controller] in context with path [/Hibernate-J2EE-Annotation] threw exception
org.hibernate.exception.SQLGrammarException: could not retrieve snapshot: [com.connection.Employee#1]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1039)
    at org.hibernate.engine.StatefulPersistenceContext.getDatabaseSnapshot(StatefulPersistenceContext.java:232)
    at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:189)
    at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:487)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:84)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
    at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
    at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
    at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:495)
    at com.connection.EmpDao.addData(EmpDao.java:12)
    at com.connection.controller.doPost(controller.java:52)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    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.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:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    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:1008)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:662)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.csl_emp' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2293)
    at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1012)
    ... 28 more
4

2 回答 2

1

在您的配置文件中添加此属性:

<property name="hibernate.hbm2ddl.auto" value="update" />

而且,这些非常有用:

<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
于 2013-09-12T06:37:44.653 回答
0

从休眠文档

如下更改您的配置文件属性

  <property name="hibernate.hbm2ddl.auto" value="create"/>

代替

<property name="hbm2ddl.auto">true</property>
于 2013-09-12T07:09:30.227 回答