您的位置:首页 > 数据库

hibernate 反向生成数据库表

2013-11-20 10:42 288 查看
hibernate配置属性中,hibernate.hbm2ddl.auto可以帮助你实现正向工程,即由java代码生成数据库脚本,进而生成具体的表结构.

在hibernate.cfg.xml中:

java 代码

[html] view
plaincopy

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="dataSource" ref="dataSource"/>

<!-- model path-->

<property name="mappingDirectoryLocations">

<list>

<value>classpath*:/com/my/myprj/model/</value>

</list>

</property>

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>

<prop key="hibernate.query.substitutions">true 'Y', false 'N'</prop>

<!-- show the sql

<prop key="hibernate.show_sql">true</prop>

-->

<!-- Create/update the database tables automatically when the JVM starts up-->

<prop key="hibernate.hbm2ddl.auto">create</prop>

<!-- Turn batching off for better error messages under PostgreSQL

<prop key="hibernate.jdbc.batch_size">0</prop> -->

</props>

</property>

</bean>

第一种解释:

<prop key="hibernate.hbm2ddl.auto">create</prop>

就这一句配置就行了哈,一般第一次启动后就注释掉哈

create:表示启动的时候先drop,再create

create-drop: 也表示创建,只不过再系统关闭前执行一下drop

update: 这个操作启动的时候会去检查schema是否一致,如果不一致会做scheme更新

validate: 启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异常,并不做更新


第二种解释:

其实这个参数的作用主要用于:自动创建|更新|验证数据库表结构。

它包含4个属性:
create : 会根据你的model类来生成表,但是每次运行都会删除上一次的表,重新生成表,哪怕2次没有任何改变

create-drop : 根据model类生成表,但是sessionFactory一关闭,表就自动删除

update : 最常用的属性,也根据model类生成表,即使表结构改变了,表中的行仍然存在,不会删除以前的行

validate : 只会和数据库中的表进行比较,不会创建新表,但是会插入新值

如果没有此方面的需求建议set value="none".
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: