【ssm框架】Service業務邏輯層&&Mybatis對映層
阿新 • • 發佈:2019-02-08
Service層
通常業務處理的程式碼並不直接放在controller層中,那樣會顯得職責不單一,不方便維護。Service業務邏輯層通常用來處理各種各樣的業務邏輯。我們將最基本的增刪改查抽取出來,作為一個基類放在BaseService層中,這樣子類就不用再去重複這些程式碼,如果有其他需求再自行擴充套件即可。
public class BaseModel implements Serializable{ private Long id; private Timestamp cdate; private Timestamp mdate; private Boolean isValid; //省略set/get方法 } public class BaseService<T extendsBaseModel> { @Autowired BaseMapper<T> mapper; protected final Logger log =LoggerFactory.getLogger(this.getClass()); public List<T> listAll() throwsException{ log.info("===查詢所有實體記錄==="); return mapper.selectAll(); } public void delete(Long id) throwsException{ log.info("===刪除實體記錄==="); T record = queryById(id); record.setMdate(newTimestamp(System.currentTimeMillis())); record.setValid(false); mapper.updateByPrimaryKey(record); } public T insert(T record) throws Exception{ log.info("===儲存實體記錄==="); record.setCdate(newTimestamp(System.currentTimeMillis())); record.setMdate(newTimestamp(System.currentTimeMillis())); record.setValid(true); mapper.insert(record); return record; } public T update(T record) throwsException{ log.info("===更新實體記錄==="); record.setMdate(newTimestamp(System.currentTimeMillis())); if (record.getId() == null) { record.setCdate(newTimestamp(System.currentTimeMillis())); mapper.insert(record); } else { mapper.updateByPrimaryKey(record); } return record; } @SuppressWarnings("unchecked") public T queryById(Long id) throwsException{ log.info("===根據id查詢實體記錄==="); T record =mapper.selectByPrimaryKey(id); return record; } }
Mapper對映層
我們知道Mybatis是通過定義介面,通過反射機制來實現它的資料庫操作的。既然是資料庫操作,那麼最基本的增刪改查自然是所有Mapper都會有的,因此也可以抽取出基類。
public interface BaseMapper<T extends BaseModel>{ List<T> selectAll(); int deleteByPrimaryKey(Long id); T selectByPrimaryKey(Long id); int insert(T t); int updateByPrimaryKey(T t); }
建好表之後,具體的model,mapper介面,mapper.xml都可以通過Mybatis的程式碼自動生成來構建。關於mybatis generator的配置,可參考http://www.jianshu.com/p/e09d2370b796