Hibernate數據庫對象的創建與導出
那么如何通過對象對數據庫進行各種對象的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(); } |
總結:簡單粗暴!
posted on 2014-03-20 11:29 順其自然EVO 閱讀(321) 評論(0) 編輯 收藏 所屬分類: 數據庫