Java 休眠错误org.Hibernate.exception.sqlgrammareexception:表。。。不';不存在
这里的Java学生正在从事一个基本的Hibernate项目。 服务器:tomcat IDE:eclipsejuno 我试图将一些数据持久化到mySql数据库中,但每次单击“进程”按钮时都会出现错误。 错误:org.hibernate.exception.sqlgrammareexception:表'timdowney.requestdatapersistent'不存在 我的DB的名称是:timdowney,它确实存在。 我的Db服务器工作正常,因为我已经用其他jdbc应用程序对它进行了测试 所以,我的问题是:为什么我会得到一个错误,声明表'timdowney.requestdatapersistent'不存在,而timdowney不是一个表,而是我的DB名称 仅供参考:requestdatapersistent是我的bean类 我同意,这是一个很大的代码Java 休眠错误org.Hibernate.exception.sqlgrammareexception:表。。。不';不存在,java,hibernate,invocationtargetexception,Java,Hibernate,Invocationtargetexception,这里的Java学生正在从事一个基本的Hibernate项目。 服务器:tomcat IDE:eclipsejuno 我试图将一些数据持久化到mySql数据库中,但每次单击“进程”按钮时都会出现错误。 错误:org.hibernate.exception.sqlgrammareexception:表'timdowney.requestdatapersistent'不存在 我的DB的名称是:timdowney,它确实存在。 我的Db服务器工作正常,因为我已经用其他jdbc应用程序对它进行了测试 所以
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.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();
}
}
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;
}
}
HiernateHelper类
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();
}
}
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;
}
}
org.hibernate.exception.sqlgrammareexception:表'timdowney.requestdatapersistent'不存在
错误表示schemaname.tablename不存在,所以您的架构是timdowney,表名是requestdatapersistent。由于您没有在实体中指定任何表,它使用bean名称作为实体名称,所以您需要执行以下操作之一:
@实体
@Table(name=“request\u data\u persistent”)
希望这能解决你的问题
干杯 如果注释不适用于您,您可以尝试创建类似于以下内容的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>
等等
这是最明显的错误消息。数据库中没有表requestdatapersistent
。用@Table
注释您的类。但是,hibernate不应该自动创建它吗?如果您不使用@Table
注释或一些xml映射配置告诉它作为表使用什么,则不会。您必须对列执行相同的操作。好的,我将尝试@table注释。@table注释允许指定默认值以外的其他表名。但它不会创建表。如果要自动创建表,请在文档中查找hibernate.hbm2ddl
。或者更好的方法是,使用SQL脚本自己创建表。它看起来已经不一样了。新错误:调用ch5.persistentData.RequestDataPersistent.idI的setter时发生IllegalArgumentException。我添加了@Table注释,但现在我收到一个新的错误消息。请查看更新的堆栈跟踪。感谢您的帮助。我以前使用过映射文件,它工作得很好,但现在希望使用注释进行编码。