Hibernate错误org.hibernate.exception.SQLGrammarException:表...不存在

时间:2013-07-24 20:19:19

标签: java hibernate invocationtargetexception

Java Student在这里从事基本的Hibernate项目。 服务器:tomcat IDE:Eclipse Juno

我正在尝试将一些数据保存到mySql Db中,但每次单击进程按钮时都会出现错误。 错误: org.hibernate.exception.SQLGrammarException:表'timdowney.requestdatapersistent'不存在

我的数据库的名称是: timdowney ,它确实存在。 我的Db服务器工作正常,因为我已经使用其他jdbc应用程序进行了测试。

所以,我的问题是:为什么我得到一个错误,指出Table'timpdowney.requestdatapersistent'不存在,而timdowney不是一个表而是我的数据库名称?

fyi: requestdatapersistent 是我的bean类

这是一个很大的代码,我同意。

Button Method Error
org.hibernate.exception.SQLGrammarException: Table 'timdowney.requestdatapersistent' doesn't exist
java.lang.reflect.InvocationTargetException
    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 shared.HelperBaseCh4.invokeButtonMethod(HelperBaseCh4.java:155)
    at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:124)
    at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:133)
    at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:100)
    at ch5.persistentData.ControllerHelper.doPost(ControllerHelper.java:128)
    at ch5.persistentData.configure.ControllerHelper.doPost(ControllerHelper.java:40)
    at ch5.persistentData.configure.Controller.doPost(Controller.java:39)
    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:947)
    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:1009)
    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.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.exception.SQLGrammarException: Table 'timdowney.requestdatapersistent' doesn't exist
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
    at com.sun.proxy.$Proxy18.executeQuery(Unknown Source)
    at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1469)
    at org.hibernate.engine.internal.StatefulPersistenceContext.getDatabaseSnapshot(StatefulPersistenceContext.java:301)
    at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:217)
    at org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:495)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:100)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:641)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:633)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:629)
    at shared.HibernateHelper.updateDB(HibernateHelper.java:135)
    at ch5.persistentData.ControllerHelper.processMethod(ControllerHelper.java:101)
    ... 29 more
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'timdowney.requestdatapersistent' doesn't exist
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2934)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1616)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1708)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3255)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1293)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1428)
    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.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
    ... 42 more    

的hibernate.cfg.xml

<?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="dialect">
      org.hibernate.dialect.MySQLDialect
    </property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/timdowney</property>
    <property name="connection.username">root</property>
    <property name="connection.password">pasapas2005</property>
    <property name="c3p0.min_size">1</property>
    <property name="c3p0.max_size">5</property>
    <property name="c3p0.timeout">300</property>
    <property name="c3p0.max_statements">50</property>
    <property name="c3p0.idle_test_period">300</property>
  </session-factory>
</hibernate-configuration>    

我的豆类

package ch5.persistentData;

import java.io.Serializable;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

@Entity
public class RequestDataPersistent extends shared.PersistentBase implements
        Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    protected String hobby;
    protected String aversion;
    private Long id;

    public RequestDataPersistent() {
    }

    @Id
    public Long getId() {
        return id;
    }

    protected void setId(Long id) {
        this.id = id;
    }

    @Pattern(regexp = ".*\\S.*", message = "cannot be empty")
    @NotNull
    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    @Pattern(regexp = ".*\\S.*", message = "cannot be empty")
    @NotNull
    public String getAversion() {
        return aversion;
    }

    public void setAversion(String aversion) {
        this.aversion = aversion;
    }

    protected int daysPerWeek;

    @Min(value = 1, message = "must be greater than 1, if this is a hobby.")
    @Max(value = 7, message = "cannot be greater than 7. A week only has 7 days.")
    public int getDaysPerWeek() {
        return daysPerWeek;
    }

    public void setDaysPerWeek(int daysPerWeek) {
        this.daysPerWeek = daysPerWeek;
    }
}       

控制器助手类

package ch5.persistentData.configure;

import ch5.persistentData.RequestDataPersistent;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import shared.HibernateHelper;

public class ControllerHelper
        extends ch5.persistentData.ControllerHelper {

    public ControllerHelper(
            HttpServlet servlet,
            HttpServletRequest request,
            HttpServletResponse response) {
        super(servlet, request, response);
    }

    static public void initHibernate(HttpServlet servlet) {
    boolean create = 
        Boolean.parseBoolean(servlet.getInitParameter("create"));
        if (create) {
            HibernateHelper.createTable(RequestDataPersistent.class);
        }
        HibernateHelper.initSessionFactory(RequestDataPersistent.class);
    }

    @Override
    public void doGet()
            throws ServletException, java.io.IOException 
    {
        super.doGet();
    }

    @Override
    public void doPost()
            throws ServletException, java.io.IOException 
    {
        super.doPost();
    }
}    

HiernateHelper类

package shared;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.criterion.Restrictions;

public class HibernateHelper {

    static protected Logger log = Logger
            .getLogger("bytesizebook.webdev.hibernate");
    static protected List<Class> listClasses = new ArrayList<Class>();
    static protected SessionFactory sessionFactory;

    static public void initSessionFactory(Properties props, Class... mappings) {
        if (addMappings(listClasses, mappings)) {
            closeSessionFactory(sessionFactory);
            sessionFactory = createFactory(props, listClasses);
        }
    }

    static public void initSessionFactory(Class... mappings) {
        initSessionFactory(null, mappings);
    }

    static public void createTable(Properties props, Class... mappings) {
        List<Class> tempList = new ArrayList<Class>();
        SessionFactory tempFactory = null;

        addMappings(tempList, mappings);
        if (props == null) {
            props = new Properties();
        }
        props.setProperty(Environment.HBM2DDL_AUTO, "create");
        tempFactory = createFactory(props, tempList);
        closeSessionFactory(tempFactory);
    }

    static public void createTable(Class... mappings) {
        createTable(null, mappings);
    }

    static protected boolean addMappings(List<Class> list, Class... mappings) {
        boolean bNewClass = false;
        for (Class mapping : mappings) {
            if (!list.contains(mapping)) {
                list.add(mapping);
                bNewClass = true;
            }
        }
        return bNewClass;
    }

    static protected SessionFactory createFactory(Properties props,
            List<Class> list) {
        SessionFactory factory = null;
        Configuration cfg = new Configuration();
        try {
            if (props != null) {
                cfg.addProperties(props);
            }
            configureFromFile(cfg);
            for (Class mapping : list) {
                cfg.addAnnotatedClass(mapping);
            }
            factory = buildFactory(cfg);
        } catch (Exception ex) {
            // Make sure you log the exception, as it might be swallowed
            log.error("SessionFactory creation failed.", ex);
            closeSessionFactory(factory);
            factory = null;
            // hibernate has a runtime exception for handling problems with
            // initialisation. Cast the ex to HibernateException and raise,
            // since the root problem is a Hibernate problem.
            throw new HibernateException(ex);
        }
        return factory;
    }

    static protected void configureFromFile(Configuration cfg) {
        try {
            cfg.configure();
        } catch (HibernateException ex) {
            if (ex.getMessage().equals("/hibernate.cfg.xml not found")) {
                log.warn(ex.getMessage());
            } else {
                log.error("Error in hibernate " + "configuration file.", ex);
                throw ex;
            }
        }
    }

    static protected SessionFactory buildFactory(Configuration cfg)
            throws Exception {
        SessionFactory factory = null;
        try {
            factory = cfg.buildSessionFactory();
        } catch (Exception ex) {
            closeSessionFactory(factory);
            factory = null;
            throw ex;
        }
        return factory;
    }

    static public void closeSessionFactory(SessionFactory factory) {
        if (factory != null) {
            factory.close();
        }
    }

    static public void closeFactory() {
        closeSessionFactory(sessionFactory);
    }

    static public void updateDB(Object obj) {
        Session session = null;
        try {
            session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();

            session.saveOrUpdate(obj);

            tx.commit();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    static public void updateDB(java.util.List list) {

        Session session = null;
        try {
            session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();

            for (Object obj : list) {
                session.saveOrUpdate(obj);
            }

            tx.commit();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    static public void saveDB(Object obj) {
        Session session = null;
        try {
            session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();

            session.save(obj);

            tx.commit();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    static public void removeDB(Object obj) {
        Session session = null;
        try {
            session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();

            session.delete(obj);

            tx.commit();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    static public java.util.List getListData(Class classBean, String strKey,
            Object value) {
        java.util.List result = new java.util.ArrayList();

        Session session = null;
        try {
            session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();

            Criteria criteria = session.createCriteria(classBean);
            if (strKey != null) {
                criteria.add(Restrictions.like(strKey, value));
            }
            result = criteria.list();

            tx.commit();

        } finally {
            if (session != null) {
                session.close();
            }
        }
        return result;
    }

    static public java.util.List getListData(Class classBean, String strKey1,
            Object value1, String strKey2, Object value2) {
        java.util.List result = new java.util.ArrayList();
        boolean withParent = false;
        int age = 0;
        Session session = null;
        try {
            session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();

            Criteria criteria = session.createCriteria(classBean);
            if (strKey1 != null) {
                criteria.add(Restrictions.like(strKey1, value1));
            }
            if (strKey2 != null) {
                criteria.add(Restrictions.like(strKey2, value2));
            }

            result = criteria.list();

            tx.commit();

        } finally {
            if (session != null) {
                session.close();
            }
        }
        return result;
    }

    static public java.util.List getListData(Class classBean) {
        return getListData(classBean, null, null);
    }

    static public Object getFirstMatch(Class classBean, String strKey,
            Object value) {

        Object result = null;
        Session session = null;
        try {
            session = sessionFactory.openSession();
            Transaction tx = session.beginTransaction();

            Criteria criteria = session.createCriteria(classBean);
            if (strKey != null) {
                criteria.add(Restrictions.like(strKey, value));
            }
            criteria.setMaxResults(1);
            result = criteria.uniqueResult();

            tx.commit();

        } finally {
            if (session != null) {
                session.close();
            }
        }
        return result;
    }

    static public Object getFirstMatch(Object data, String strKey, Object value) {
        return getFirstMatch(data.getClass(), strKey, value);
    }

    static public Object getKeyData(Class beanClass, long itemId) {
        Object data = null;
        Session session = sessionFactory.openSession();

        data = session.get(beanClass, itemId);

        session.close();

        return data;
    }

    static public boolean isSessionOpen() {
        return sessionFactory != null;
    }
}  
在我的bean类中添加@Table注释后的新堆栈跟踪

Button Method Error
org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of ch5.persistentData.RequestDataPersistent.id

java.lang.reflect.InvocationTargetException
    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 shared.HelperBaseCh4.invokeButtonMethod(HelperBaseCh4.java:155)
    at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:124)
    at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:133)
    at shared.HelperBaseCh4.executeButtonMethod(HelperBaseCh4.java:100)
    at ch5.persistentData.ControllerHelper.doPost(ControllerHelper.java:128)
    at ch5.persistentData.configure.ControllerHelper.doPost(ControllerHelper.java:40)
    at ch5.persistentData.configure.Controller.doPost(Controller.java:39)
    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:947)
    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:1009)
    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.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of ch5.persistentData.RequestDataPersistent.id
    at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:119)
    at org.hibernate.mapping.Component$ValueGenerationPlan.execute(Component.java:436)
    at org.hibernate.id.CompositeNestedGeneratedValueGenerator.generate(CompositeNestedGeneratedValueGenerator.java:121)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:118)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:641)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:633)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:629)
    at shared.HibernateHelper.updateDB(HibernateHelper.java:130)
    at ch5.persistentData.ControllerHelper.processMethod(ControllerHelper.java:101)
    ... 29 more
Caused by: java.lang.IllegalArgumentException: argument type mismatch
    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.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:65)
    ... 41 more

2 个答案:

答案 0 :(得分:1)

  

org.hibernate.exception.SQLGrammarException:表'timdowney.requestdatapersistent'不存在

错误说schemaname.tablename不存在,因此您的架构是timdowney,表名是requestdatapersistent。由于您未在Entity中指定任何表,因此使用bean名称作为实体名称,您需要执行以下任一操作:

  1. 创建名为requestdatapersistent
  2. 的表
  3. 如果有不同的表名,则使用以下内容在注释中提供:
  4. @Entity

    @Table(name="request_data_persistent")

    希望这可以解决您的问题。

    干杯!!

答案 1 :(得分:0)

如果注释不适合你,你可以尝试创建类似于下面的hibernate映射文件:

    <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="ch5.persistentData.RequestDataPersistent" 
                 table="tablename" catalog="timdowney ">
        <id name="ID" type="java.lang.Long">
            <column name="id" length="10" not-null="true" unique="true" />
        </id>
        <property name="EventName" type="String">
            <column name="eventname" length="10" not-null="true" unique="false" />
        </property>
        <property name="hobby" type="String">
            <column name="hobby" length="20" not-null="true"
                unique="false" />
        </property>
        ....and so on

    </class>

</hibernate-mapping>