您的位置:首页 > 数据库

junit测试中Hibernate报错SQL Error:1146,SQLState:42S02

qzcsu 2016-10-05 21:51 85 查看
此问题困扰笔者很久,希望能帮到一些初学者。

先不多说了,初学Hibernate框架写了一个Demo,结果一直运行不出来想要的结果。

先描述下环境:在eclipse中添加了Hibernate的插件,然后使用的是Hibernate-4.3.11版本。数据库使用的是MySQL5.5.28。在数据库中先创建好一个数据库名字叫:hibernate,里面没有任何东西。

下面首先贴出我的项目列表和文件代码,以及错误



以下是每个文件的具体代码

News.java文件代码如下

package com.hibernate.pojo;

import java.sql.Date;

public class News {

private Integer id;
private String title;
private String author;
private Date date;

public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}

public News(String title, String author, Date date) {
super();
this.title = title;
this.author = author;
this.date = date;
}

public News() {}

@Override
public String toString() {
return "News [id=" + id + ", title=" + title + ", author=" + author
+ ", date=" + date + "]";
}

}


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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<!-- 配置hibernate基本信息 -->
<!-- 配置数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>

<!-- 指定自动生成数据表的策略 -->
<property name="hbm2ddl.auto">update</property>

<!-- 是否在控制台打印SQL语句 -->
<property name="show_sql">true</property>

<!-- 是否对SQL进行格式化 -->
<property name="format_sql">true</property>

<!-- 指定关联的 .hbm.xml文件 -->
<mapping resource="com/hibernate/pojo/News.hbm.xml" />

</session-factory>

</hibernate-configuration>


News.hbm.xml文件代码如下:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-10-5 18:37:01 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping package="com.hibernate.pojo" >
<class name="News" table="NEWS">

<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>

<property name="title" type="java.lang.String">
<column name="TITLE" />
</property>

<property name="author" type="java.lang.String">
<column name="AUTHOR" />
</property>

<property name="date" type="java.sql.Date">
<column name="DATE" />
</property>

</class>
</hibernate-mapping>


HibernateTest.java文件代码如下:

package com.hibernate.test;

import java.sql.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.Test;

import com.hibernate.pojo.News;

public class HibernateTest {

@Test
public void test() {

//1.获取sessionFactory
//a.获取hibernate的上下文对象
Configuration configuration = new Configuration().configure();
//b.通过上下文对象创建serviceRegistry对象
ServiceRegistry serviceRegistry =
new ServiceRegistryBuilder().applySettings(configuration.getProperties())
.buildServiceRegistry();
//c.获取sessionFactory
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

//2.获取session
Session session = sessionFactory.openSession();

//3.开启事务
Transaction transaction = session.beginTransaction();

//4.执行逻辑
News news = new News("hibernate", "qinzhe", new Date(new java.util.Date().getTime()));
session.save(news);

//5.提交事务
transaction.commit();

//6.关闭session
session.close();

//7.关闭sessionFactory
sessionFactory.close();
}

}


结果运行这个测试类报了以下错误:

十月 05, 2016 10:02:10 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
十月 05, 2016 10:02:10 下午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.11.Final}
十月 05, 2016 10:02:10 下午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
十月 05, 2016 10:02:10 下午 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
十月 05, 2016 10:02:10 下午 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
十月 05, 2016 10:02:10 下午 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
十月 05, 2016 10:02:10 下午 org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
十月 05, 2016 10:02:10 下午 org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: com/hibernate/pojo/News.hbm.xml
十月 05, 2016 10:02:10 下午 org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
十月 05, 2016 10:02:10 下午 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
十月 05, 2016 10:02:11 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
十月 05, 2016 10:02:11 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hibernate]
十月 05, 2016 10:02:11 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
十月 05, 2016 10:02:11 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
十月 05, 2016 10:02:11 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
十月 05, 2016 10:02:11 下午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLInnoDBDialect
十月 05, 2016 10:02:11 下午 org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
十月 05, 2016 10:02:11 下午 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
十月 05, 2016 10:02:11 下午 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
十月 05, 2016 10:02:13 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
十月 05, 2016 10:02:13 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
十月 05, 2016 10:02:13 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
十月 05, 2016 10:02:13 下午 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: NEWS
十月 05, 2016 10:02:13 下午 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: NEWS
十月 05, 2016 10:02:13 下午 org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: NEWS
十月 05, 2016 10:02:14 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: HHH000388: Unsuccessful: create table NEWS (ID integer not null auto_increment, TITLE varchar(255), AUTHOR varchar(255), DATE date, primary key (ID)) type=InnoDB
十月 05, 2016 10:02:14 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: 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 7
十月 05, 2016 10:02:14 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate:
insert
into
NEWS
(TITLE, AUTHOR, DATE)
values
(?, ?, ?)
十月 05, 2016 10:02:14 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
十月 05, 2016 10:02:14 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Table 'hibernate.news' doesn't exist
十月 05, 2016 10:02:14 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler logWarning
WARN: SQL Warning Code: 1146, SQLState: 42S02
十月 05, 2016 10:02:14 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler logWarning
WARN: Table 'hibernate.news' doesn't exist


总结

照理来说我写了以上代码,hibernate会自动帮我创建news表,并且插入一条数据的。结果总是报错说hibernate.news表不存在。

网上查找了很多资料,有以下几种说法:

有种说法是在News.hbm.xml文件中的class标签中:



经测试怎么改都没有效果,当然对于我来说是没有什么用的,但是你可以试试看,不一定你就成功了。反正我直接没写这个属性。

还有网友说是数据库的大小写敏感问题,这个我没去试过,因为MySQL好像不存在这回事情,但是对于你可能有效。

还有网友说是数据库名字或者表的名字和数据库中使用的关键字可能有冲突,结果我去试了试还是没用。

最后我终于找出来的原因是hibernate.cfg.xml文件中的这行代码

<!-- 配置hibernate基本信息 -->
<!-- 配置数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>


网上后来百度了一下org.hibernate.dialect.MySQLInnoDBDialect和org.hibernate.dialect.MySQLDialect 两个方言的区别,说MySQLDialect是兼容性方言,MySQLInnoDBDialect支持事务的方言版。但是如果数据库版本是5.5以下,就可以直接用,如果是5.5版本及以上,需要改成MySQL5InnoDBDialect。 结果马上cmd上去

mysql --version


一看版本是5.5.28。然后将数据库方言改为MySQL5InnoDBDialect。果然一切问题都解决了。
相关文章推荐