gpt4 book ai didi

java - Hibernate错误org.hibernate.exception.SQLGrammarException : Table . ..不存在

转载 作者:行者123 更新时间:2023-12-01 14:18:47 24 4
gpt4 key购买 nike

Java 学生正在开发一个基本的 Hibernate 项目。服务器:tomcatIDE:Eclipse Juno

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

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

所以,我的问题是:为什么我收到一条错误消息,指出表“timdowney.requestdatapersistent”不存在,而 timdowney 不是表而是我的数据库名称?

仅供引用: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>

我的 Bean 类

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

Controller 辅助类

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

最佳答案

org.hibernate.exception.SQLGrammarException: Table 'timdowney.requestdatapersistent' doesn't exist

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

  1. 创建一个名为 requestdatapersistent 的表
  2. 如果有不同的表名称,则使用以下方式在注释中提供:

@Entity

@Table(name="request_data_persistent")

希望这能解决您的问题。

干杯!!

关于java - Hibernate错误org.hibernate.exception.SQLGrammarException : Table . ..不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17844064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com