最近这两天,一直在搞hibernate,被 其中一个问题困扰了好久.在网上找了好久,一直都没有找到可行的方法,把jdk,jre,tomcat,装了拆,拆了装,可就是搞不好.实在是没有办法,又重新建了一个项目来测试,,从一点一滴开始试.所有的代码全部都手写,,,,可是问题依旧还在.
之所以一直没有找到解决办法,其实是自己的思维一直局限在一处,,,一直在想着hibernate只要把配置文件配置好,它就可以自己在数据库创建表结构,自己增删改查,相当的方便,可是自己 当时成功了,为什么这次却一而再再而三的失败呢....后来再想,要不创建一个数据库,然后再创建一个表.直接用hibernate插入数据试试....没想到竟然没有报错,当时那个心情啊....
现将错误代码贴上:
WARN: Table 'myapp.user' doesn't exist Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91) at org.hibernate.id.IncrementGenerator.initializePreviousValueHolder(IncrementGenerator.java:132) at org.hibernate.id.IncrementGenerator.generate(IncrementGenerator.java:69) at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:118) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209) at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194) at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49) at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90) at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715) at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707) at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702) at com.huangchao.model.HibernateTest.main(HibernateTest.java:21)
上面显示的错误提示是不能执行结果集,,,,,,,原因就是没有创建表,那当然就不能执行了.
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'myapp.user' doesn't exist at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at com.mysql.jdbc.Util.handleNewInstance(Util.java:404) at com.mysql.jdbc.Util.getInstance(Util.java:387) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2551) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1962) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82) ... 12 more
看到没有,这上面显示的就是表不存在....
经检查.....hibernate.cfg.xml中有一个配置是这样写的:
<property name="hibernate.hbm2dll">create</property>
一看,不对呀,如果要想自动建表的话那应该是这样的啊:
<property name="hibernate.hbm2ddl.auto">create</property>
原来是自己少打了.auto啊,千万要注意,.auto是不能少的,重要的事说三遍:
.auto是不能少
.auto是不能少
.auto是不能少
最后得出的结论是:
hibernate在没有手动为数据库创建特定的表的时候,且在配置文件里没有设置自动创建表,,这时就会报错.
完整代码如下:
Model:User.java
package com.huangchao.model; public class User { private int id ; private String username ; private String password ; public User(){ } public User(String username,String password){ this.username = username; this.password = password; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Mapping:User.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> <class name="com.huangchao.model.User" table="user"> <id name="id" type="int"> <column name="id"></column> <generator class="increment"></generator> </id> <property name="username" type="java.lang.String"> <column name="username" /> </property> <property name="password" type="java.lang.String"> <column name="password" /> </property> </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://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 设置数据库的基本连接信息 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql:///myapp?characterEncoding=utf8</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <!-- 设定数据库言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 设置数据 库的SQL语句的格式--> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl">create</property> <mapping resource="com/huangchao/model/User.hbm.xml"/> </session-factory> </hibernate-configuration>
Test:HibernateTest.java
package com.huangchao.model; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class HibernateTest { public static void main(String[] args) { Configuration config = new Configuration().configure(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build(); SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); Session session = sessionFactory.openSession(); User user = new User("zhoubin","33333"); session.save(user); Transaction tx = session.beginTransaction(); tx.commit(); session.close(); } }