问题描述:
在调试hibernate的时候发现设置hbm2ddl.auto设置为update是不能工作,eclipse中报如下错误:
Hibernate: insert into news (title, content) values (?, ?)
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [com.ericsson.ewanbao.News]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
...................
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernate.news' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
...............
问题分析:
经检查数据库发现,news表确实创建不成功,可见hbm2ddl.auto设置为update没有能够建立表
解决步骤:
1.把mysql的general-log打开,这样可以跟踪所有的sql语句;
2.再次执行程序,在general-log的最后发现如下sql语句:
3 Query SHOW FULL TABLES FROM `hibernate` LIKE 'news'
3 Query create table news (id integer not null auto_increment, title varchar(255), content varchar(255), primary key (id)) type=InnoDB
3 Query SHOW FULL TABLES FROM `hibernate` LIKE 'PROBABLYNOT'
3 Query SET autocommit=0
3 Query SET autocommit=1
3 Query SET autocommit=0
3 Query insert into news (title, content) values ('???????', '???????????!')
3 Query SHOW FULL TABLES FROM `hibernate` LIKE 'PROBABLYNOT'
3.可以发现hibernate已经发送了见表语句给数据库,为什么建表没有成功了?尝试拷贝这些建表语句到sql控制台执行,得到如下结果:
mysql> create table news (id integer not null auto_increment, title varchar(255), content varchar(255), primary key (id)
) type=InnoDB;
ERROR 1064 (42000): 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=InnoDB' at line 1
4.可以看到是sql语句错误,经分析发现是hibernate.dialect的设置错误,原先设置为org.hibernate.dialect.MySQLInnoDBDialect,应该修改为org.hibernate.dialect.MySQL5InnoDBDialect