Udemy 課程Microservices with Spring 21

Creating JPA Entity & build some test data

ZONGRU Li
4 min readJul 10, 2019

暫時地將security部分dependency注解

而專案建立時已經有納入JPA與H2 DB相關的dependency了

接著為了看到JPA對應的SQL訊息及H2 DB內容(透過UI)

在application.properties加上

spring.jpa.show-sql=true

spring.h2.console.enabled=true

原本的User Bean內容如下:

更正為以下:

多幾個annotation

執行RestfulWebServicesApplication見到

create table user (

id integer not null,

birth_date timestamp,

name varchar(255),

primary key (id))

透過console有以上資訊,即確認table可以正常建立後

開始塞些假資料

在resources目錄加上data.sql

重新執行RestfulWebServicesApplication

就會發現在塞第一筆就報錯

因為要改單引號

重新執行後進到url:localhost:8089/h2-console

直接不帶密碼按連線

以上table的JPA設定與假資料就準備完成

複製現有UserResource為UserJPAResource

並必免兩者的API衝突,網址列都加上/jpa

並針對JPA加入一個新的UserRepository Interface

回頭UserJPAResource把這個Interface Autowired進去

並改寫後面所有取值方法

當然也要確定功能都正常:

另外deleteUser跟createUser

確認deleteUser執行正常

用retrieveAllUsers來確認:

確認剩下兩筆

接著執行新增USER:

上面出錯原因在於JPA將自動生成第一個序號欄位,起始值為1開始

但是目前已經有序號為1之資料

所以將User Bean做修改

原本的id是用@GeneratedValue

改為@GeneratedValue(strategy = GenerationType.IDENTITY):

一樣刪了id為2後再次地執行新增USER

再次確認所有Users

看起來符合我們需要!!

之前非JPA用的以下code就可以刪除

--

--

ZONGRU Li
ZONGRU Li

Written by ZONGRU Li

2022/11/17 開源部分個人筆記給LINE "Java程式語言討論區"社群,希望能對社群的技術學習做一點點貢獻.(掩面....記得退訂閱!

No responses yet