由現有資料庫產生Spring Boot Entity (eclipse)
前言
大部份教學都是先產Entity,再連接資料庫由Entity自動產生資料表
若反過來,已經有現成資料表,要反產Entity呢?
就需要借助IDE的套件來實現了
且產出的檔案,只需要加一裝飾器,即可直接依JPA 規範操作資料表!
一、eclipse 安裝套件Dali JPA Tools
- 打開
eclipse help->Install New Software- 選到
eclipse update,搜尋dali,勾選最新版本 - 靜待安裝完畢。完成後須重啟
eclipse![install-dali-jpa]()
二、將專案轉換成JPA
- 在package Explorer頁籤,對專案按右鍵
Configure->Convert to JPA Project![convert-to-jpa-1]()
- 彈出
JPA Facet視窗,確認JPA有勾選(預設會勾起),接著一路next到最後![convert-to-jpa-2]()
- 點擊
Add connection,此處以DB2為例![convert-to-jpa-3]()
- 點擊最右邊的
三角形,選到JAR List頁籤,匯入DB2的JAR檔 (若為其他資料庫,則須選擇對應資料庫的JAR檔)![convert-to-jpa-4]()
- 輸入資料庫連線資料,並按下
Test Connection,成功後按下Finish![convert-to-jpa-5]()
- 在
JPA implementation下的type,選擇Disable Library Configuration![convert-to-jpa-6]()
三、由Table 產生 entity
- 對專案按
右鍵->JPA Tools->Generate Entities from Tables![gen-entity-1]()
- 選擇要轉換的
schema、table - 指定放置package(須事先建立好),按下
finish,完成建立![gen-entity-3]()
- 打開產生出的java檔,於
@Entity下方增加@Table(name="所選的TABLE_NAME", schema="所選的SCHEMA"),接下來就可以依Spring Boot JPA規範操作資料表
@Entity
+@Table(name="DEMO_TABLE", schema="DEMO")
@NamedQuery(name="Demo", query="SELECT d FROM Demo d")
public class Demo implements Serializable { /** ...內容省略... */ }
參考資料
How to Generate JPA Entities from database tables with Eclipse and Spring Boot?








