昨天已經設定好JPA/Hibernate EntityManager,接著介紹persistence層要哪些coding,依慣例Web應用程式會建立Repository層專門存取資料庫以及Service層來呼叫不同Respository來取得資料,通常在model下在建立兩個package: repository及service,並建立相對應的interface以及實作interface的class,package目錄如下圖:
DCNRepository以及DCNService為介面,僅定義需實作的方法,目前暫時只定義新增以及列出所有資料,Code如下:
DCNRepository.java
package tw.blogger.springtech.springmvc.model.repository;
import java.util.List;
import tw.blogger.springtech.springmvc.model.DCN;
public interface DCNRepository{
void save(DCN dcn);
List<DCN> findAll();
}
DCNService.java
public interface DCNService{
void add(DCN dcn);
List<DCN> findAll();
}
定義好介面後,接著新增各個對應的實作class,class名稱後面多Imp以區別,為了之後DCNRepositoryImp及DCNServiceImp可以被注入Controller,或是換句話說,在Controller裡要Autowired DCNRepository及DCNService,兩個class前面必須分別加入@Repository及@Service,Component Scan就能註冊為bean,方便injection操作,code如下:
package tw.blogger.springtech.springmvc.model.repository;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tw.blogger.springtech.springmvc.model.DCN;
DCNRepositoryImp.java
@Repository("DCNRepository")
@Transactional(propagation =Propagation.REQUIRED)
public class DCNRepositoryImp implements DCNRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
public void save(DCN dcn) {
// TODO Auto-generated method stub
entityManager.persist(dcn);
}
@Override
public List<DCN> findAll() {
// TODO Auto-generated method stub
Query query=entityManager.createQuery("select d from DCN d");
List<DCN> dcns=(List<DCN>)query.getResultList();
return dcns;
}
}
DCNServiceImp.java
package tw.blogger.springtech.springmvc.model.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tw.blogger.springtech.springmvc.model.DCN;
import tw.blogger.springtech.springmvc.model.repository.DCNRepository;
@Service("DCNService")
public class DCNServiceImp implements DCNService {
@Autowired
private DCNRepository dcnRepository;
@Override
public void add(DCN dcn) {
// TODO Auto-generated method stub
dcnRepository.save(dcn);
}
@Override
public List<DCN> findAll() {
// TODO Auto-generated method stub
return dcnRepository.findAll();
}
}
簡單Model層大致就完成了,其實已經有在寫Controller的code以及jsp,只是發生最可怕的404,除錯中,希望明天可以解決,還蠻奇怪的,之前用xml組態檔做RequestMapping都沒問題,這次用Java Config,結果竟然有問題,不過除錯也是學習的一環啦,加上這也是第一次用EntityManager,之前練習時用Session Factory是沒問題的,不過通常好像很少一次就到位,總是會跑出Exception。