基於ssm框架的個人部落格(5)--Dao層設計及測試
阿新 • • 發佈:2019-01-26
前臺的頁面完成了一部分,那麼是時候開發Dao層了,前面我們提到了mybatis的逆向工程,也展示了一些逆向生成的一些配置檔案,實體類......現在我們就基於ssm框架,對Dao進行開發,由於程式碼比較簡單,在此不做解釋,直接看註釋。
貼上程式碼
package testDao; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.lailai.common.utils.EasyUIDataGridResult; import com.lailai.entity.TBlogtype; import com.lailai.entity.TBlogtypeExample; import com.lailai.mapper.TBlogtypeMapper; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:conf/applicationContext-dao.xml") public class testDao { /** * 注入TBlogtypeMapper bean */ @Autowired private TBlogtypeMapper blogtypeMapper; /** * 增加部落格 */ @Test public void addBlog(){ System.out.println(blogtypeMapper); TBlogtype tBlogtype = new TBlogtype(); tBlogtype.setId(3); //tBlogtype.setOrdernum(ordernum); tBlogtype.setTypename("java web"); int insert = blogtypeMapper.insert(tBlogtype); System.out.println(insert); } /** * 刪除部落格 */ @Test public void deleteBlog(){ System.out.println(blogtypeMapper); int n = blogtypeMapper.deleteByPrimaryKey(new Integer(3)); System.out.println(n); } /** * 更新部落格 */ @Test public void updateBlog(){ TBlogtype tBlogtype = new TBlogtype(); tBlogtype.setTypename("c#"); tBlogtype.setId(new Integer(3)); int n = blogtypeMapper.updateByPrimaryKey(tBlogtype); System.out.println(n); } /** * 按id查詢部落格 */ @Test public void selectBlogByid( ){ TBlogtype n = blogtypeMapper.selectByPrimaryKey(new Integer(3)); System.out.println(n.toString()); } /** * 分頁查詢部落格(所有部落格) * 注意:這裡有些註釋現在不需要理解可以,作用是封裝資料到前臺 */ @Test public void selectByPage(){ //設定分頁資訊 PageHelper.startPage(1,2); //執行查詢 TBlogtypeExample example = new TBlogtypeExample(); List<TBlogtype> list = blogtypeMapper.selectByExample(example); //建立一個返回值物件 //EasyUIDataGridResult result = new EasyUIDataGridResult(); //result.setRows(list); //取分頁結果 PageInfo<TBlogtype> pageInfo = new PageInfo<>(list); //取總記錄數 long total = pageInfo.getTotal(); //result.setTotal(total); //System.out.println(total); System.out.println(pageInfo.getPageSize()); System.out.println(pageInfo.getPageNum()); System.out.println(pageInfo.getTotal()); System.out.println(pageInfo.getList()); //Page{pageNum=1, pageSize=2, startRow=0, endRow=2, total=5, pages=3} //System.out.println(result.getTotal()); //return result; } }
上述測試,使用了
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:conf/applicationContext-dao.xml")
這種寫法是為了讓測試在Spring容器環境下執行。
Spring的容器環境是什麼?
比如常見的 Service Dao Action,都在Spring容器裡,junit需要將他們拿到,並且使用來測試。
這些Dao,都是能夠經得起測試的,現在我們來編輯bolog相關的Dao