利用hibernate的映射文件,自動生成oracle數據庫表

第一種:利用hibernate根據映射文件生成表

1、首先下載oracle的jdbc驅動包,本例子採用的oracle 11g,所以需要下載ojdbc6.jar版本。

2、在class根目錄下創建hibernate.cfg.xml文件,內容如下:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@192.168.22.177:1521:jcms</property>
<property name="connection.username">lpz</property>
<property name="connection.password">123456</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="connection.characterEncoding">utf-8</property> 
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="net/cnki/tpi/cms/dbxml/Advert.hbm.xml"/>
</session-factory>
</hibernate-configuration>

3、編寫生成數據表的類

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class CreateDBUtil {
public static void main(String[]arggs){
Configuration cfg = new Configuration().configure();  
        SchemaExport schemaExport= new SchemaExport(cfg);  
        schemaExport.create(true, true); 
}
}


第二種利用spring配置文件,配置hibernate,來生成表

<!--hibernate.hbm2ddl.auto的值
                validate       加載hibernate時,驗證創建數據庫表結構
create         每次加載hibernate,重新創建數據庫表結構,這就是導致數據庫表數據丟失的原因。
create-drop    加載hibernate時創建,退出是刪除表結構
update         加載hibernate自動更新數據庫結構  
-->
                <prop key="hibernate.hbm2ddl.auto">validate</prop>

當啓動服務器的時候,就會校驗或者創建或者更新數據表


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章