我是hibernate的新手,我必须从中获得一些奇怪的行为,下面就是这个场景。
我的java文件是,
UserDetails.java: -
package org.mahesh.test;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class UserDetails {
@Id
private int userId;
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
HibernateTest.java是,
package org.mahesh.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.mahesh.securifi.UserDetails;
public class HibernateTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("Mahesh");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
hibernate.cfg.xml是,
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/employee</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="org.mahesh.securifi.UserDetails"/>
</session-factory>
</hibernate-configuration>
完整堆栈跟踪是,
Mar 24, 2017 10:28:20 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.9.Final}
Mar 24, 2017 10:28:20 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 24, 2017 10:28:20 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Mar 24, 2017 10:28:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm pl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Mar 24, 2017 10:28:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm pl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/employee]
Mar 24, 2017 10:28:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm pl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Mar 24, 2017 10:28:20 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm pl buildCreator
INFO: HHH10001003: Autocommit mode: false
Mar 24, 2017 10:28:20 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Mar 24, 2017 10:28:20 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Mar 24, 2017 10:28:20 AM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Hibernate: drop table if exists UserDetails
Mar 24, 2017 10:28:21 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorN onJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProvi derJdbcConnectionAccess@40db2a24] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table UserDetails (userId integer not null, userName varchar(255), primary key (userId)) type=MyISAM
Mar 24, 2017 10:28:21 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorN onJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@22356acd] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Mar 24, 2017 10:28:21 AM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreato rImpl.java:440)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreat orImpl.java:424)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCr eatorImpl.java:315)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreat orImpl.java:166)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImp l.java:135)
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImp l.java:121)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAct ion(SchemaManagementToolCoordinator.java:155)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaMana gementToolCoordinator.java:72)
at org.hibernate.internal.SessionFactoryImpl.<init> (SessionFactoryImpl.java:309)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilde rImpl.java:445)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at org.mahesh.hibernate.HibernateTest.main(HibernateTest.java:16)
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'type=MyISAM' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3206)
at com.mysql.jdbc.Statement.execute(Statement.java:727)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(Genera tionTargetToDatabase.java:54)
... 13 more
Mar 24, 2017 10:28:21 AM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@6e4566 f1'
Hibernate: insert into UserDetails (userName, userId) values (?, ?)
Mar 24, 2017 10:28:21 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Mar 24, 2017 10:28:21 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Table 'employee.userdetails' doesn't exist
Mar 24, 2017 10:28:21 AM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Mar 24, 2017 10:28:21 AM org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.SQLGrammarException: could not execute statement]
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.jav a:147)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.jav a:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.jav a:162)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1434)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:484)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl. java:3190)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java: 2404)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompleti on(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransa ctionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordi natorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransa ctionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java :38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransa ctionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransa ctionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl .java:68)
at org.mahesh.hibernate.HibernateTest.main(HibernateTest.java:20)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3003)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3503)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:586)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:460)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
... 9 more
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'employee.userdetails' doesn't exist
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1604)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1519)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1504)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetRe turnImpl.java:205)
... 18 more
在运行时出现此错误。
答案 0 :(得分:2)
尝试在hibernate.cfg.cml中更改方言
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
这应解决问题。
如果您想使用MyISAM
package com.mahesh.dialect;
import org.hibernate.dialect.MySQLMyISAMDialect
class MySQL5MyISAMDialect extends MySQLMyISAMDialect {
String getTableTypeString() {
" ENGINE=MyISAM"
}
}
并将方言设为
<!-- SQL dialect -->
<property name="dialect">com.mahesh.dialect.MySQL5MyISAMDialect</property>
答案 1 :(得分:1)
{@ 1}}已被弃用。
不推荐使用&#34; hibernate.dialect.storage_engine = innodb&#34;而是环境变量或JVM系统属性。
您可以将org.hibernate.dialect.MySQL5InnoDBDialect
放入 hibernate.properties 中,也可以将其设置为环境变量。
答案 2 :(得分:0)
此异常是因为数据库中没有UserDetails表 如果你想hibernate将创建表,然后在你的hibernate.cfg.xml文件中添加下面的属性
#!groovy
import jenkins.model.*
import hudson.security.*
import jenkins.install.*;
import hudson.triggers.SCMTrigger;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
def instance = Jenkins.getInstance()
println "--> creating local user 'admin'"
def hudsonRealm = new HudsonPrivateSecurityRealm(false)
hudsonRealm.createAccount('admin','admin')
instance.setSecurityRealm(hudsonRealm)
def strategy = new FullControlOnceLoggedInAuthorizationStrategy()
instance.setAuthorizationStrategy(strategy)
instance.save()
jenkins = Jenkins.instance;
workflowJob = new WorkflowJob(jenkins, "workflow2");
jobName = "create-dsl-job2";
gitTrigger = new SCMTrigger("* * * * *");
dslProject = new hudson.model.FreeStyleProject(jenkins, jobName);
dslProject.addTrigger(gitTrigger);
jenkins.add(dslProject, jobName);
job = jenkins.getItem(jobName)
builders = job.getBuildersList()
hudson.tasks.Shell newShell = new hudson.tasks.Shell("echo \"Hello\" ")
builders.replace(newShell)
gitTrigger.start(dslProject, true);
您可以选择hbm2ddl.auto值validate |更新|创建|创建降 取决于您的要求。
答案 3 :(得分:0)
当我将数据库从MySQL 5.1升级到5.7时,我也遇到了CommandAcceptanceException和SQLGrammarException。我在hibernate.cfg.xml
中更改了方言<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
早些时候&#34; org.hibernate.dialect.MySQLDialect&#34;。它解决了这个问题。