Hibernate无法自动创建表

来源:互联网 发布:战斗机的分类 知乎 编辑:程序博客网 时间:2024/05/18 18:15

首先介绍其中的一个属性hbm2ddl.auto,这个就是这个方案的核心属性,有四个值:create,create-drop,update,validate;

<!-- 启动时删数据库中的表,然后创建,退出时不删除数据表<property name="hibernate.hbm2ddl.auto">create</property>-->
<!-- 启动时删数据库中的表,然后创建,退出时自动删除所有表<property name="hibernate.hbm2ddl.auto">create-drop</property>-->
<!-- 自动修改,如果表结构与实体类不一致,那么就修改表使它们一致,数据会保留<property name="hibernate.hbm2ddl.auto">update</property>-->
<!-- 自动校验,如果表结构与实体类不一致,那么不做任何操作,报错<property name="hibernate.hbm2ddl.auto">validate</property>-->

本来这个属性的产生是为了测试数据的,我觉得利用这个自动建表非常方便。利用这段代码:

<property name="hibernate.hbm2ddl.auto">create</property>
但是,在实际开发中却会碰到无法自动创建数据库表的情况,其中一种情况是:由于实体类的属性中出现了sql关键字,hibernate将不会生成ddl来创建表结构。

这里写上解决办法:
1.<!-- DB schema will be updated if needed 自动创建表 -->
<property name="hbm2ddl.auto">update</property>

这里是update不是create,create没有去测试,看网上都是用的update

2.如果这是这么做那么很可能会报错,报错内容基本如下

Caused by: com.mysql.jdbc.exceptions.jdbc4.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 5

造成这个的原因是type=InnoDB,网上搜索了之后,原来是type=MyISAM 是5.0之前使用的,我的数据库是5.5的,这个时候需要把hibernate中mysql的方言改一下
原来的:<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

改成:<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>