基於spring-mybatis-data-common基架快速搭建web應用


spring-mybatis-data-common做了哪些操作

1.日志依據層級歸類輸出,支持擴展

2.spring-mybatis持久層基礎接口集成,支持擴展

3.常用業務接口定義,支持擴展.

只是一個簡單的常用操作的集合(CRUD +Pager),方便springmybatis項目的整合開發.關於spring-mybatis的整合在插件的configuration中有實例,直接copy出來修改就可以用.

實例展示

1.引入spring-mybatis-data-common-1.0.jar包 下載地址http://files.cnblogs.com/dennisit/spring-mybatis-data-common-1.0%E6%8F%92%E4%BB%B6.7z

copy插件configuration中的log4j.properties文件到自己項目中根據自己需要放置,實例中放置在WEB-INF/property文件夾下,web.xml指定配置

     <!-- config log4j-->
     <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/property/log4j.properties</param-value>
    </context-param>

    <!-- log4j listener -->
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

springmvc的整合,可以直接從插件configurationcopy出來修改.都是以往的普通操作流程

2.自定義實體類.如實例中我定義的實體為Article.

3.依賴插件做持久層

package com.spring.mybatis.data.common.demo.dao; import com.spring.mybatis.data.common.dao.BaseCudDao; import com.spring.mybatis.data.common.dao.BaseReadDao; import com.spring.mybatis.data.common.demo.domain.Article; public interface ArticleDao extends BaseCudDao<Article>,BaseReadDao<Article>{ //...可以自己擴展更多接口操作
}

插件中BaseCudDao接口定義了CUD操作

/** * mybatis persistence for base cud operate * * @author dennisit@163.com * * @param <T> */
public interface BaseCudDao<T extends Serializable> { // add entity
    public Integer insert(T entity) throws DaoException; // update entity 
    public Integer update(T entity) throws DaoException; // delete entity
    public Integer delete(Long id) throws DaoException; }

插件中BaseReadDao接口定義了Read操作

/** * mybatis persistence for base read operate * @author dennisit@163.com * * @param <T> */
public interface BaseReadDao<T extends Serializable> { // query entity by id
    public T selectById(Long id) throws DaoException; // query entity by condition
    public List<T> find(@Param("object") T t, @Param("start") int start, @Param("size") int size) throws DaoException; // query entity collection size by condition
    public Integer findCount(@Param("object") T t) throws DaoException; }

繼承插件接口,之后我們做自己的實現即可,當然可以自己擴展更多的接口做持久層.實例接口實現

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.spring.mybatis.data.common.demo.dao.ArticleDao">
    
  <!-- 插入數據,返回主鍵Id -->  
  <insert id="insert" parameterType="article" useGeneratedKeys="true" keyProperty="id" flushCache="true"> INSERT INTO tb_article( title , content , createDate) VALUES( #{title}, #{content}, #{createDate} ) </insert>
  
  <delete id="delete" parameterType="long" flushCache="true"> DELETE FROM tb_article WHERE id=#{id} </delete>
  
  <select id="selectById" parameterType="long" resultType="article"> SELECT id AS id,title AS title,content AS content,createDate AS createDate FROM tb_article WHERE id=#{id} </select>
  
  <select id="find" resultType="article" useCache="true"> SELECT id AS id,title AS title,content AS content,createDate AS createDate FROM tb_article WHERE 1=1 <if test="object.title!= null and ''!=object.title">
        <![CDATA[ AND title = #{object.title} ]]>
    </if>
      <if test="object.content!= null and ''!=object.content">
        <![CDATA[ AND content = #{object.content} ]]>
    </if>
    <if test="object.createDate!= null and ''!=object.createDate">
        <![CDATA[ AND createDate = #{object.createDate} ]]>
    </if> LIMIT #{start},#{size} </select>
    
  <select id="findCount" resultType="int" > SELECT count(1) FROM tb_article WHERE 1=1 <if test="object.title!= null and ''!=object.title">
        <![CDATA[ AND title = #{object.title} ]]>
    </if>
      <if test="object.content!= null and ''!=object.content">
        <![CDATA[ AND content = #{object.content} ]]>
    </if>
    <if test="object.createDate!= null and ''!=object.createDate">
        <![CDATA[ AND createDate = #{object.createDate} ]]>
    </if>
  </select>

  <update id="update" parameterType="article" flushCache="true"> UPDATE tb_article <set>
          <if test="object.title!= null and ''!=object.title">
            <![CDATA[ title = #{object.title}, ]]>
        </if>
          <if test="object.content!= null and ''!=object.content">
            <![CDATA[ content = #{object.content}, ]]>
        </if>
        <if test="object.createDate!= null and ''!=object.createDate">
            <![CDATA[ createDate = #{object.createDate} ]]>
        </if>
      </set> WHERE id=#{object.id} </update>
  
</mapper>
View Code

這里需要說明的是namespace指定的是對應的的接口,id為接口中的方法,使用AS 別名映射成實體類中的屬性.

關於Mybatis掃描持久層時的配置

    <!-- 配置持久層操作文件掃描路徑,basePackage指定的是持久層Dao所有接口存放文檔 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <property name="basePackage" value="com.spring.mybatis.data.common.demo.dao" />
    </bean>
    
    <!-- 在遵守命名規范的前提下,使用掃描domain包,省去別名配置文件別名形式: 對應的domain類首字母小寫 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
         <property name="typeAliasesPackage" value="com.spring.mybatis.data.common.demo.domain"/>
    </bean>

如果只做上面配置的話,默認掃描時回去basePackage下面去尋找對應的mapper xml文件,所以上面配置需要我們將xml文件和對應的接口放置在同一個目錄下,如果沒有在同一個目錄下,且自定義別名的話,可以使用如下配置

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:/mybatis/mybatis-config.xml" />
        <property name="mapperLocations" value="classpath:/mybatis/map/*.xml" />
    </bean>

4.依賴插件做service

package com.spring.mybatis.data.common.demo.service; import com.spring.mybatis.data.common.demo.domain.Article; import com.spring.mybatis.data.common.service.BaseService; public interface ArticleService extends BaseService<Article, Long>{ //此處可以自己擴展更多的業務接口
}

實例service實現

package com.spring.mybatis.data.common.demo.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.mybatis.data.common.demo.dao.ArticleDao; import com.spring.mybatis.data.common.demo.domain.Article; import com.spring.mybatis.data.common.demo.service.ArticleService; import com.spring.mybatis.data.common.exception.DaoException; import com.spring.mybatis.data.common.exception.ServiceException; import com.spring.mybatis.data.common.log.LogHandler; import com.spring.mybatis.data.common.page.Page; /** * * @author dennisit@163.com * */ @Service("articleService") public class ArticleServiceImpl implements ArticleService{ @Autowired private ArticleDao articleDao; @Override public int deleteById(Long id) throws ServiceException { try { return this.articleDao.delete(id); } catch (DaoException e) { LogHandler.daoLogError("delete by id error , id = " + id, e); } return 0; } @Override public int save(Article entity) throws ServiceException { try { return this.articleDao.insert(entity); } catch (DaoException e) { LogHandler.daoLogError("save entity error, entity = " + entity, e); } return 0; } @Override public Article selectById(Long id) throws ServiceException { try { return this.articleDao.selectById(id); } catch (DaoException e) { LogHandler.daoLogError("select by id error, id = " + id, e); } return null; } /* (non-Javadoc) * @see com.spring.mybatis.data.common.service.BaseService#selectObject(java.io.Serializable) */ @Override public Article selectObject(Article t) throws ServiceException { // TODO Auto-generated method stub
        return null; } @Override public Page<Article> selectPage(Article t, Integer pageNow, Integer pageSize)throws ServiceException { Page<Article> page = null; try { List<Article> list = this.articleDao.find(t, (pageNow-1)*pageSize, pageSize); int recordTotal = this.articleDao.findCount(t); page = new Page<Article>(list, recordTotal, pageNow,pageSize); } catch (DaoException e) { LogHandler.daoLogError("select page error, entity = " 
                    + t + "pageNow=" + pageNow + "pageSize=" + pageSize, e); } return page; } @Override public int update(Article entity) throws ServiceException { try { return this.articleDao.update(entity); } catch (DaoException e) { LogHandler.daoLogError("update entity error, entity = " + entity, e); } return 0; } /* (non-Javadoc) * @see com.spring.mybatis.data.common.service.BaseService#selectPage(java.io.Serializable, java.lang.Long, java.lang.Integer) */ @Override public int deleteObject(Article entity) throws ServiceException { // TODO Auto-generated method stub
        return 0; } public void setArticleDao(ArticleDao articleDao) { this.articleDao = articleDao; } }
View Code

因為插件中帶有分頁插件,所以可以使用下面操作,實現分頁數據獲取

    List<Article> list = this.articleDao.find(t, (pageNow-1)*pageSize, pageSize); int recordTotal = this.articleDao.findCount(t); Page<Article> page = new Page<Article>(list, recordTotal, pageNow,pageSize);

5.控制層根據自己需要,實例使用springmvc實現,給出實例代碼如下

package com.spring.mybatis.data.common.demo.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.spring.mybatis.data.common.controller.BaseMultiController; import com.spring.mybatis.data.common.demo.domain.Article; import com.spring.mybatis.data.common.demo.service.ArticleService; import com.spring.mybatis.data.common.exception.ServiceException; import com.spring.mybatis.data.common.log.LogHandler; import com.spring.mybatis.data.common.page.Page; @Controller @RequestMapping(value="/article") public class ArticleController extends BaseMultiController{ @Autowired private ArticleService articleService; /** * <dl> * <dt>支持的請求處理格式</dt> * <dd>http://localhost:8080/spring-mybatis-data-common-demo-web/article/detail-1325.html</dd> * <dd>http://localhost:8080/spring-mybatis-data-common-demo-web/article/1325/detail</dd> * <dl> * * 根據Id查詢 * @param request * @param response * @param id * @return
     */ @RequestMapping(value={"/{id:\\d+}/detail","/detail-{id:\\d+}.html"}, method={RequestMethod.GET}) public ModelAndView detailArticle(HttpServletRequest request, HttpServletResponse response,@PathVariable("id") Long id){ Map<String,Object> map = new HashMap<String, Object>(); try { Article article = this.articleService.selectById(id); map.put("article",article); } catch (ServiceException e) { LogHandler.serviceLogError("select entity by id error, id = " + id, e); } String viewPath = "article/detail"; return toView(viewPath, map); } /** * <dl> * <dt>支持的請求處理格式</dt> * <dd>http://localhost:8080/spring-mybatis-data-common-demo-web/article/delete-2-1325.html</dd> * <dd>http://localhost:8080/spring-mybatis-data-common-demo-web/article/2-1325/delete</dd> * <dl> * 刪除某頁的某個記錄 * @param request * @param response * @param id * @return
     */ @RequestMapping(value={"/{pageNow:\\d+}-{id:\\d+}/delete","/delete-{pageNow:\\d+}-{id:\\d+}.html"}, method={RequestMethod.GET}) public ModelAndView deleteArticle(HttpServletRequest request, HttpServletResponse response,@PathVariable("pageNow") Integer pageNow, @PathVariable("id") Long id){ Map<String,Object> map = new HashMap<String, Object>(); try { int result  = this.articleService.deleteById(id); if(result>0){ LogHandler.ctrlLogInfo("刪除記錄總數:" + result); map.put("message", "刪除成功"); } map.put("message", "刪除失敗"); } catch (ServiceException e) { LogHandler.serviceLogError("delete entity by id error, id = " + id, e); map.put("message", "刪除失敗"); } String redirectUrl = "../page-" + pageNow + ".html"; return redirectView(redirectUrl); } /** * <dl> * <dt>支持的請求處理格式</dt> * <dd>http://localhost:8080/spring-mybatis-data-common-demo-web/article/page-1.html</dd> * <dd>http://localhost:8080/spring-mybatis-data-common-demo-web/article/1/page</dd> * <dl> * * 分頁查詢 * * @param request * @param response * @param pageNow * @return
     */ @RequestMapping(value={"/page/{pageNow:\\d+}","page-{pageNow:\\d+}.html"},method={RequestMethod.GET,RequestMethod.POST}) public ModelAndView selectArticle(HttpServletRequest request,HttpServletResponse response,@PathVariable("pageNow") Integer pageNow, @ModelAttribute("article") Article article){ Map<String,Object> map = new HashMap<String, Object>(); Page<Article> page = null; //Article article = new Article();
        try { LogHandler.ctrlLogInfo("查詢條件:" + article); page = this.articleService.selectPage(article, pageNow, pageSize); System.out.println(page); map.put("page", page); List<Article> items = page.getItems(); if(null!=items){ for(Article at: items){ LogHandler.ctrlLogInfo(at.getTitle() + "-" + at.getContent()); } } } catch (ServiceException e) { LogHandler.serviceLogError("query by page , condition =" + article,e); } String viewPath = "article/lists"; return toView(viewPath, map); } /** * 添加新對象 * @param request * @param response * @param article * @return
     */ @RequestMapping(value={"/add","/add.html"},method={RequestMethod.POST}) public ModelAndView updateArticle(HttpServletRequest request,HttpServletResponse response,@ModelAttribute("article") Article article){ Map<String,Object> map = new HashMap<String, Object>(); try { int optNum = this.articleService.save(article); if(optNum > 0){ map.put("message", "article saved success"); } } catch (ServiceException e) { map.put("message", "article saved error"); LogHandler.serviceLogError("save entity error, entity =" + article,e); } String viewPath = "article/lists"; return toView(viewPath, map); } /** * <dl> * <dt>支持的請求處理格式</dt> * <dd>localhost:8080/spring-mybatis-data-common-demo-web/article/message/1/page</dd> * <dd>localhost:8080/spring-mybatis-data-common-demo-web/article/message/page-1.html</dd> * <dl> * * @param request * @param response * @param id * @return
     */ @RequestMapping(value={"/message/{pageNow:\\d+}/page","/message/page-{pageNow:\\d+}.html"}, method={RequestMethod.GET}) public @ResponseBody String pageMessage(HttpServletRequest request, HttpServletResponse response,@PathVariable("pageNow") Integer pageNow){ response.setContentType("text/html; charset=utf-8"); response.setCharacterEncoding("UTF-8"); Page<Article> page = null; Article article = new Article(); try { page = this.articleService.selectPage(article, pageNow, pageSize); StringBuffer tmp = new StringBuffer("第" + pageNow + "頁的結果集列表如下:<br/>"); List<Article> items = page.getItems(); if(null!=items){ for(Article at: items){ tmp.append(at.getTitle() + "-" + at.getContent()).append("<br/>"); } } return tmp.toString(); } catch (ServiceException e) { LogHandler.serviceLogError("query by page , condition =" + article,e); } return "沒有結果集"; } public void setArticleService(ArticleService articleService) { this.articleService = articleService; } }

實例展示完畢.

插件只是常用操作的定義集合,沒有特別操作,不過如果簡單的mvc應用,使用插件只做實現即可,還算方便把,自己鬧着玩的.用來減少個人代碼重復量.

實例地址http://files.cnblogs.com/dennisit/spring-mybatis-data-common-demo.7z

轉載請注明出處:[http://www.cnblogs.com/dennisit/p/3720706.html]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM