hibernate中annotation模式SchemaExport无法生成表的原因(ORA-02261)

hibernate中annotation方式SchemaExport无法生成表的原因(ORA-02261)
引用
主要原因分析如下:

1.ID的注解中, @Column(name = "ID", nullable = false, unique = true, insertable = true, precision = 22, scale = 0)注解中绝对不能出现 unique = true 这个属性

记得:一定要移除unique = true

2.表名可能是Oracle数据库的关键字,比如表名是user,order,这时候建议给表名加前缀,比如:t_user,t_order

3. hibernate.cfg.xml 中一定要配置如下信息(非常关键,全靠这个配置才能生产表结构):

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

4. 记得把PoJO添加到 hibernate.cfg.xml 中

<mapping class="com.dvn.li.hiberUse.model.Customer" />
<mapping class="com.dvn.li.hiberUse.model.Order" />

5.Annotation要使用AnnotationConfiguration,XML的格式是使用Configuration的

demo如下:

SchemaExport export = new SchemaExport(new AnnotationConfiguration()
     .configure());
export.create(true, true);


备注:

第一种情况是最难查找出来的,一旦使用了unique = true,程序可以正常的执行倒出表的语句,并且后台打印了SQL语句,可是数据库就是没有,无论怎么刷新也没有;

这时候把SQL复制到数据库中执行,反而会提示:

ORA-02261: 表中已存在这样的唯一关键字或主键

崩溃吧!

移除ID设置中的unique = true就搞定啦!

------------------------------------------

其实在项目的开发中,使用SchemaExport产生数据库表结构基本很少,因为数据库都是在项目Coding前定义好的;

1.Hibernate的SchemaExport接口的主要作用是测试使用;

2.如果你从网上下载了一个工程,但是没有提供建表语句,OK,它就是不错的选择,自动生成表结构!

3.如果希望改变数据库,重新生成数据库表,OK,SchemaExport也可以;比如项目工程用oracle数据,但是在家里调试时候没有安装Oracle数据库,只有MySql数据库,这时候只要修改了hibernate.cfg.xml 的数据库连接地址,用户名,密码,驱动,方言,就可以再生产对应新的数据库的表结构;--------但是,代码却需要一定的改动,因为如果没有采用HQL语句,hibernate是做不到跨数据库滴,比如代码中sql使用了oracle的专有函数,在mysql中就无法运行。