利用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>

当启动服务器的时候,就会校验或者创建或者更新数据表


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