hibernate自动建表到数据库及spring下自动建表到数据库
来源:互联网 发布:淘宝摄影单反相机 编辑:程序博客网 时间:2024/06/07 02:17
Hibernate支持自动建表,在开发阶段很方便,可以保证hbm与数据库表结构的自动同步。
如何使用呢?很简单,只要在hibernate.cfg.xml里加上如下代码
Xml代码<property name="hbm2ddl.auto">update</property>
update:表示自动根据model对象来更新表结构,启动hibernate时会自动检查数据库,如果缺少表,则自动建表;如果表里缺少列,则自动添加列。
还有其他的参数:
create:启动hibernate时,自动删除原来的表,新建所有的表,所以每次启动后的以前数据都会丢失。
create-drop:启动hibernate时,自动创建表,程序关闭时,自动把相应的表都删除。所以程序结束时,表和数据也不会再存在。
PS:数据库要预先建立好,因为hibernate只会建表,不会建库
==========================================
表结构和数据总是在程序执行的时候无端的修改,折腾了好长时间,查了很长时间hibernate的数据库映射文件和接口程序,始终没有发现有什么错误,到最后才发现了它!
<property name="hibernate.hbm2ddl.auto" value="update" />
解释如下:
hibernate.hbm2ddl.auto Automatically validate or export schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly. eg. validate | update | create | create-drop
其实这个参数的作用主要用于:自动创建|更新|验证数据库表结构。
如果没有此方面的需求建议set value="none".
其它几个参数的意思:
validate 加载hibernate时,验证创建数据库表结构
create 每次加载hibernate,重新创建数据库表结构
create-drop 加载hibernate时创建,退出是删除表结构
update 加载hibernate自动更新数据库结构
如果发现数据库表丢失或新增,请检查hibernate.hbm2ddl.auto的配置 可设置 <property name="hibernate.hbm2ddl.auto" value="none" />
建议在开发环境下使用,在生产环境下去掉。
优点:
1、自动创建新表
2、自动创建新字段
3、自动修改字段类型
缺点:
1、不会自动删除表
2、不会自动删除字段
3、自动创建的新字段只能是在最后。
针对缺点的建议:定期把数据库清空(删除所有表),然后启动项目,让hibernate自动创建表结构和索引,当然一些初始化数据需要手工导入。
补充:如果使用spring管理hibernate,如何建表到数据库:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
起作用的是<prop key="hibernate.hbm2ddl.auto">update</prop>这一句,自动建表
- hibernate自动建表到数据库及spring下自动建表到数据库
- spring+hibernate自动生成数据库表结构
- spring+hibernate自动生成数据库表结构
- hibernate自动创建数据库
- hibernate自动创建数据库
- Spring集成hibernate映射表自动创建数据库表
- hibernate自动重新连接数据库
- hibernate自动导出数据库表
- hibernate自动生成数据库表
- Hibernate自动创建数据库表
- Hibernate自动生成数据库表
- hibernate 自动生成数据库表
- 【Hibernate】自动生成数据库表
- mysql数据库下hibernate无法自动建表
- linux下自动备份数据库
- asp下自动安装数据库
- Hibernate不能自动建表解决办法及Hibernate不同数据库的连接及SQL方言
- Hibernate 自动生成数据库表过程分析
- 使用Docker构建Gitlab私服
- gym 100820G Racing Gems(二维LIS,好题)
- VBA:Excel使用SQL进行查询
- 别名(Alias)
- 处理机的三级调度
- hibernate自动建表到数据库及spring下自动建表到数据库
- NYOJ2 括号配对问题
- 1046. Shortest Distance
- 巧妙使用WilliamChart绘制出只有两个圆角的柱状图
- Java高并发程序设计笔记(三)之Volatile与Lock
- LeetCode 442 --- Find All Duplicates in an Array
- 1047. Student List for Course
- 知名的开源apm(Application Performance Management)工具
- LintCode之最长公共子串(Longest Common Substring)