基于spring-mybatis-data-common基架快速搭建web应用
spring-mybatis-data-common做了哪些操作
1.日志依据层级归类输出,支持扩展
2.spring-mybatis持久层基础接口集成,支持扩展
3.常用业务接口定义,支持扩展.
只是一个简单的常用操作的集合(CRUD +Pager),方便spring与mybatis项目的整合开发.关于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的整合,可以直接从插件configuration中copy出来修改.都是以往的普通操作流程
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>
这里需要说明的是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;
} }
因为插件中带有分页插件,所以可以使用下面操作,实现分页数据获取
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]
基于spring-mybatis-data-common基架快速搭建web应用的更多相关文章
- SSM(SpringMVC+Spring+MyBatis)三大框架使用Maven快速搭建整合(实现数据库数据到页面进行展示)
本文介绍使用SpringMVC+Spring+MyBatis三大框架使用Maven快速搭建一个demo,实现数据从数据库中查询返回到页面进行展示的过程. 技术选型:SpringMVC+Spring+M ...
- Spring Boot入门-快速搭建web项目
Spring Boot 概述: Spring Boot makes it easy to create stand-alone, production-grade Spring based Appli ...
- Maven聚合、Maven仓库jar包以及Spring+MyBatis+JUnit+Maven整合测试的搭建过程
一.Maven将父项目创建到父项目的内部 在父项目的pom.xml上 点右键,选择maven-->new-->maven module project 二.Maven聚合 在某个项目的p ...
- 快速搭建Web环境 Angularjs + Express3 + Bootstrap3
快速搭建Web环境 Angularjs + Express3 + Bootstrap3 AngularJS体验式编程系列文章, 将介绍如何用angularjs构建一个强大的web前端系统.angula ...
- windows下如何快速搭建web.py开发框架
在windows下如何快速搭建web.py开发框架 用Python进行web开发的话有很多框架供选择,比如最出名的Django,tornado等,除了这些框架之外,有一个轻量级的框架使用起来也是非常方 ...
- 在windows下如何快速搭建web.py开发框架
在windows下如何快速搭建web.py开发框架 用Python进行web开发的话有很多框架供选择,比如最出名的Django,tornado等,除了这些框架之外,有一个轻量级的框架使用起来也是非常方 ...
- 93.快速搭建Web环境 Angularjs + Express3 + Bootstrap3
转自:https://www.cnblogs.com/wawahaha/p/3946023.html 前言 Angularjs越用越顺手,不仅代码量比jQuery少很多,而且实现思路特别清晰,构建大型 ...
- 实战基于Spring Boot 2的WebFlux和mLab搭建反应式Web
Spring Framework 5带来了新的Reactive Stack非阻塞式Web框架:Spring WebFlux.作为与Spring MVC并行使用的Web框架,Spring WebFlux ...
- SpringMVC+Spring+mybatis项目从零开始--分布式项目结构搭建
转载出处: SpringMVC+Spring+mybatis+Redis项目从零开始--分布式项目结构搭建 /** 本文为博主原创文章,如转载请附链接. **/ SSM框架web项目从零开始--分布式 ...
随机推荐
- Struts2(接受表单参数)请求数据自动封装和数据类型转换
Struts2请求数据自动封装: (1)实现原理:参数拦截器 (2)方式1:jsp表单数据填充到action中的属性: 普通的成员变量,必须给set,get可以不给的. 注意点,A ...
- (第5篇)避免协作冲突--简单易接入的Zookeeper
摘要: 众所周知,分布式的系统协作服务很难有让人满意的产品.这些协作服务产品很容易陷入一些诸如竞争选择条件或者死锁的陷阱中.那Zookeeper又是怎么解决这个问题的呢? 博主福利 给大家推荐一套ha ...
- [ZJOI2010]贪吃的老鼠
很不错的一道网络流的题目 二分答案是显然的 首先不考虑每个饼干只能一个老鼠吃 那很显然的建图就是将时间点按照开始结束的点分成2*n-1段 然后对每一段时间建m个老鼠的点,然后s-它限流,再从它到目前可 ...
- BZOJ1090 [SCOI2003]字符串折叠 区间动态规划 字符串
欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - BZOJ1090 题意概括 折叠的定义如下: 1. 一个字符串可以看成它自身的折叠.记作S 2. X(S)是X ...
- POJ - 1266 -
题目大意:给出一条圆弧上的两个端点A,B,和圆弧上两端点之间的一个点C,现在要用一块各个定点的坐标均为整数的矩形去覆盖这个圆弧,要求最小的矩形面积. 思路:叉积在本体发挥很强大的作用.首先求出三个点所 ...
- CentOS下生成密钥对(公钥、私钥)
1.公钥.私钥简述: 假设数据传输方A向数据接收方B传输数据(以A为服务器,B为客户端为例).现在B有一对密钥对(公钥和私钥),B将公钥发送给A,A通过公钥加密后将数据传给B,B收到数据后利用手里的私 ...
- Python - 利用flask搭建一个共享服务器
零.概述 我利用flask搭建了一个简易的共享服务器,分享给大家 一.python代码 import os import time from flask import Flask,render_tem ...
- ios技术篇:导航栏push遵循的三个规则
1.如果B视图有一个自定义的左侧按钮(leftBarButtonItem),则会显示这个自定义按钮 2.如果B没有自定义按钮,但是A视图的backBarButtonItem属性有自定义项,则显示这个自 ...
- python新手总结(二)
random模块 随机小数 random uniform 随机整数 randint randrange 随机抽取 choice sample 打乱顺序 shuffle random.random() ...
- python有序字典OrderedDict()
转python创建有序字典OrderedDict # -*- coding:utf-8 -*- """ python有序字典 需导入模块collections " ...