Spring MVC Repository及Service Annotation介紹

Spring MVC Repository及Service Annotation介紹

這篇文章會介紹persistence層要哪些coding,依慣例Web應用程式會建立Repository層專門存取資料庫以及Service層來呼叫不同Respository來取得資料,通常在model下在建立兩個package: repository及service,並建立相對應的interface以及實作interface的class,

package目錄如下圖:

Spring MVC Repository及Service Annotation介紹

DCNRepository以及DCNService為介面,僅定義需實作的方法,目前暫時只定義新增以及列出所有資料,Code如下:

Spring MVC Repository及Service Annotation介紹

定義好介面後,接著新增各個對應的實作class,class名稱後面多Imp以區別,為了之後DCNRepositoryImp及DCNServiceImp可以被注入Controller,或是換句話說,在Controller裡要Autowired DCNRepository及DCNService,兩個class前面必須分別加入@Repository及@Service,Component Scan就能註冊為bean,方便injection操作,code如下:

Spring MVC Repository及Service Annotation介紹

Spring MVC Repository及Service Annotation介紹

簡單Model層大致就完成了,其實已經有在寫Controller的code以及jsp,只是發生最可怕的404,除錯中,希望明天可以解決,還蠻奇怪的,之前用xml組態檔做RequestMapping都沒問題,這次用Java Config,結果竟然有問題,不過除錯也是學習的一環啦,加上這也是第一次用EntityManager,之前練習時用Session Factory是沒問題的,不過通常好像很少一次就到位,總是會跑出Exception。


分享到:


相關文章: