运行程序的结果是:Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [lee.News];
Caused by: java.sql.SQLException: Table 'hibernates.news_table' doesn't exist
奇怪的是数据没有插入成功,反而自动把表给删除了。。。。
纠结了好长时间,请懂的朋友支援,谢谢!!
mysql:
create table news_table (
news_id int primary key auto_increment,
news_title varchar(20) not null,
content varchar(50) not null );
News.java :
package lee;
public class News {
private Integer id;
private String title;
private String content;
public News() {}
public News(Integer id, String title, String content) {
this.setId(id);
this.setTitle(title);
this.setContent(content);
}
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 getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
Test.java :
package lee;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Test {
public static void main(String[] args) throws Exception
{
//实例化Configuration
Configuration conf = new Configuration().configure();
//实例化SessionFactory
SessionFactory sf = conf.buildSessionFactory();
//实例化Session
Session sess = sf.openSession();
//开始事务
Transaction tx = sess.beginTransaction();
//创建消息实例
News n = new News();
//设置消息标题和消息内容
n.setTitle("疯狂Java联盟成立了");
n.setContent("疯狂Java联盟成立了,网址是www.crazyit.org");
//保存消息
sess.save(n);
//提交事务
tx.commit();
//关闭Session
sess.close();
}
}
News.hbm.xml :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="lee">
<!-- 每个class元素对应一个持久化对象 -->
<class name="News" table="news_table">
<!-- id元素定义持久化类的标识属性 -->
<id name="id" column="news_id" unsaved-value="null">
<generator class="identity"/>
</id>
<!-- property元素定义常规属性 -->
<property name="title" column="news_title" type="string"/>
<property name="content" type="string"/>
</class>
</hibernate-mapping>
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>
<!-- 指定连接数据库的url,hibernate是连接的数据库名 -->
<property name="connection.url">jdbc:mysql://localhost/hibernates</property>