Eclipse中要集成安裝Hibernate Tools組件
如果沒有,請查看:Eclipse juno 中安裝 JBoss Tools,集成Hibernate
一.確定環境:
1.Maven3.0.5
2.Eclipse Juno,集成Jboss/Hibernate Tools
3.Oracle10g
4.Hibernate3.6.5.Final
5.JDK1.7.0_11
二.打開Hibernate Perspective視圖層
在Eclipse中打開“Hibernate Perspective“。
選擇“Windows” >> “Open Perspective” >> “Others…” , 選擇 “Hibernate“。
三.新建Hibernate Configuration 配置
1.在Hibernate Perspective中, 右鍵,選 “Add Configuration…”,彈出對話框
2.在 “Project”區域, 單擊 “Browse..” 選擇你自己的項目。
3.在 “Database Connection” 區域, 單擊 “New..”創建你自己的數據庫設定。
4.彈出Connection Profile中選Oracle ,並填寫“Name”后,Next
5.在彈出對話框中,選Driver,沒有的話要新加,此處新加Driver。
6.彈出對話框中選一個driver,如果出現“Unable to locate JAR/zip in file system as specified by the driver definition: ojdbc14.jar.”
就要在“JAR List”選項卡中刪除原有的驅動文件,重新加一下就好了。
刪除驅動文件重新添加,此處添加的是Maven倉庫中的jar包
完成后點擊OK
填寫完數據庫的相關連接后,可以點Test Connection測試是否可以連接上。
連接上如圖
7.Configuration file配置
店家“Setup”彈出“Setup configuration file”對話框,如果不存在.dfg.xml文件,可以新建
上圖點擊“Create New...”后,彈出新建cfg.xml文件對話框
創建在項目目錄下的main/java/resources下,
我的是在“maven-hibernate-demo/src/main/resources”
可以點擊next配置更具體的設置,此處我們直接Finsh
返回前一界面后,OK。記住,此處的“Hibernate Version”選項一定要選對版本,否則反向工程不會成功。
查看Hibernate Configurations視圖
四.查看src/main/resources目錄下的剛建好的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="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@yourdatabaseip:gzip</property> <property name="hibernate.connection.username">username</property> <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property> </session-factory> </hibernate-configuration>
五.生成Hibernate代碼
在“Hibernate Perspective”視圖中, 點擊 “Hibernate Code Generation Configuration”
在生成代碼框中,新建configuration,並填寫Main選項卡和Exporters選項卡,
Main中需要填寫輸出路徑等,填完的如下
console configuration選擇前邊剛配置完的Hibernate Configuration,前邊的名字是“hibernate”
Output directory選擇輸出路徑
Reverse enginner from JDBC Connection勾選
Package填寫包名
reveng.xml填寫創建hibernate.reveng.xml的位置,沒有則新建。
在Exporters選擇相應要生成的代碼
可以生成Model , mapping file (hbm) , DAO, annotation code 等等。
點Run生成代碼
生成的代碼結構如下