Hibernate数据库对象的创建与导出

Hibernate 与 数据库的关系是ORM关系,对象映射数据库。
  那么如何通过对象对数据库进行各种对象的ddl与dml操作呢?
  数据库对象操作的〈database-object ../〉+ SchemaExport
   1、hibernate.cfg.xml
<?xml version="1.0" encoding="GBK"?>
<!-- 指定Hibernate配置文件的DTD信息 -->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- hibernate- configuration是连接配置文件的根元素 -->
<hibernate-configuration>
<session-factory>
......
<!-- 根据需要自动创建数据库:如果创建表,这里必须为create -->
<property name="hbm2ddl.auto">create</property>
<!-- 显示Hibernate持久化操作所生成的 SQL -->
<property name="show_sql">true</property>
<!-- 将SQL脚本进行格式化后再输出 -->
<property name="hibernate.format_sql">true</property>
<!-- 罗列所有的映射文件 -->
<mapping resource="....../lovejk.hbm.xml"/>
</session-factory>
lt;/hibernate-configuration>
   2、lovejk.hbm.xml
<?xml version="1.0" encoding="gb2312"?>
<!-- 指定Hiberante3映射文件的DTD信息 -->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- hibernate-mapping是映射文件的根元素 -->
<hibernate-mapping>
<!-- 使用data-object元素定义数据库对象 -->
<database-object>
<!-- 定义创建数据库对象的语句 -->
<create>create table testjk(name varchar(256));</create>
<!-- 让drop元素为空,不删除任何对象 -->
<drop></drop>
<!-- 指定仅对 MySQL数据库有效 -->
<dialect-scope name="org.hibernate.dialect.MySQLDialect"/>
<dialect-scope name="org.hibernate.dialect.MySQLInnoDBDialect"/>
</database-object>
</hibernate-mapping>
   3、执行
public static void main(String[] args) throws Exception
{
//实例化Configuration,这行代码默认加载hibernate.cfg.xml文件
Configuration conf = new Configuration().configure();
//以Configuration创建SessionFactory
SessionFactory sf = conf.buildSessionFactory();
//      //创建SchemaExport对象
SchemaExport se = new SchemaExport(conf);
//      //设置输出格式良好的SQL脚本
se.setFormat(true);
//          //设置保存SQL脚本的文件名
se.setOutputFile("d:\\1.sql");
//      //输出SQL脚本,并执行SQL脚本
se.create(true, true);
sf.close();
}
   总结:简单粗暴!


最新内容请见作者的GitHub页:http://qaseven.github.io/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值