springmvc+spring+mybatis整合实例【转】

开发环境:

System:Windows server 2003

WebBrowser:IE6+、Firefox3+

JavaEE Server:tomcat5.

IDE:eclipse、MyEclipse 6.5

Database:MySQL

开发依赖库:

JavaEE5、Spring 3.0.5、Mybatis 3.0.2、myBatis-spring-1.0.0-rc2

1、 首先新建一个WebProject 命名为ssi,新建项目时,使用JavaEE5的lib库。然后手动添加需要的jar包,所需jar包如下:

2、 添加spring的监听及springMVC的核心Servlet,web.xml内容,内容如下:

org.springframework.web.context.ContextLoaderListenercontextConfigLocationclasspath:applicationContext-*.xmlspmvcorg.springframework.web.servlet.DispatcherServletspmvc*.doCharacterEncodingFilterorg.springframework.web.filter.CharacterEncodingFilterencodingutf-8CharacterEncodingFilter/*index.jsp

3、 在WEB-INF目录中添加spmvc-servlet.xml,内容如下:

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

4、 在src目录下添加applicationContext-common.xml,内容如下:

classpath:com/hoo/mapper/*.xml

上面的配置最先配置的是DataSource,这里采用的是jdbc的DataSource;

然后是SqlSessionFactoryBean,这个配置比较关键。SqlSessionFactoryBean需要注入DataSource数据源,其次还要设置configLocation也就是mybatis的xml配置文件路径,完成一些关于mybatis的配置,如settings、mappers、plugin等;

如果使用MapperScannerPostProcessor模式,会自动将basePackage中配置的包路径下的所有带有@Mapper标注的Mapper(dao)层的接口生成代理,替代原来我们的Mapper实现。

5、AccountMapper接口内容如下:

@Mapper("mapper")publicinterfaceAccountMapperextendsSqlMapper {publicListgetAllAccount();publicAccount getAccount();publicAccount getAccountById(String id);publicAccount getAccountByNames(String spring);

@Select("select * from account where username = #{name}")publicAccount getAccountByName(String name);publicvoidaddAccount(Account account);publicvoideditAccount(Account account);publicvoidremoveAccount(intid);

}

6、 实体类和account-resultmap.xml

privatestaticfinallongserialVersionUID = -7970848646314840509L;privateInteger accountId;privateInteger status;privateString username;privateString password;privateString salt;privateString email;privateInteger roleId;//getter、setter@OverridepublicString toString()

{returnthis.accountId + "#" +this.status + "#" +this.username +  "#" +this.password +  "#" +this.email +  "#" +this.salt + "#" +this.roleId;

}

account-resultmap.xml


"http://mybatis.org/dtd/mybatis-3-mapper.dtd">username, passwordinsert into account(account_id, status, username, password)

values(#{accountId}, #{status}, #{username}, #{password})select cast(random() * 10000 as Integer) a from #Tabinsert into account(account_id, status, username, password)

values(#{accountId}, #{status}, #{username}, #{password})update account set

status = #{status},

username = #{username},

password = #{password}

where account_id = #{accountId}delete from account where account_id = #{id}

7、 在src目录中添加applicationContext-beans.xml内容如下:

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

这里配置bean对象,一些不能用annotation注解的对象就可以配置在这里

8、 在src目录中添加mybatis.xml,内容如下:



在这个文件放置一些全局性的配置,如handler、objectFactory、plugin、以及mappers的映射路径(由于在applicationContext-common中的SqlSessionFactoryBean有配置mapper的location,这里就不需要配置)等

9、 定义AccountDao接口及实现代码,代码如下:

publicinterfaceAccountDao{publicbooleanaddAccount(T entity)throwsDataAccessException;publicT getAccount(Integer id)throwsDataAccessException;publicList getList()throwsDataAccessException;

}

接口实现

importjava.util.List;importjavax.inject.Inject;importorg.springframework.dao.DataAccessException;importorg.springframework.stereotype.Repository;importorg.springframework.beans.factory.annotation.Autowired;importcom.hoo.dao.AccountDao;importcom.hoo.entity.*;importcom.hoo.mapper.*;importorg.springframework.beans.factory.annotation.Qualifier;

@SuppressWarnings("unchecked")

@Repository("accountDaoImpl")publicclassAccountDaoImplimplementsAccountDao{

@Autowired(required=false)

@Qualifier("mapper")privateAccountMapper mapper;publicbooleanaddAccount(T entity)throwsDataAccessException {booleanflag=false;try{

mapper.addAccount(entity);

flag=true;

}catch(DataAccessException e)

{

flag=false;throwe;

}returnflag;

}publicT getAccount(Integer id)throwsDataAccessException {

T entity=null;try{

entity=(T)mapper.getAccountById(String.valueOf(id));

}catch(DataAccessException e)

{throwe;      }returnentity;

}publicList getList()throwsDataAccessException {return(List)mapper.getAllAccount();

}

}

10、 服务层AccountBiz接口及实现代码

接口:

publicinterfaceAccountBiz{publicbooleanaddAccount(T entity)throwsDataAccessException;publicT getAccount(Integer id)throwsDataAccessException;publicList getList()throwsDataAccessException;

}

实现代码:

packagecom.hoo.biz.impl;importjava.util.List;importorg.springframework.dao.DataAccessException;importcom.hoo.biz.AccountBiz;importcom.hoo.entity.*;importjavax.inject.Inject;importcom.hoo.dao.*;importorg.springframework.stereotype.Service;importcom.hoo.exception.BizException;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;

@Service("accountBizImpl")publicclassAccountBizImplimplementsAccountBiz{

@Autowired

@Qualifier("accountDaoImpl")privateAccountDaodao;publicbooleanaddAccount(T entity)throwsDataAccessException {if(entity==null){thrownewBizException(Account.class.getName()+"对象参数为empty!");

}returndao.addAccount(entity);

}publicT getAccount(Integer id)throwsDataAccessException {returndao.getAccount(id);

}publicList getList()throwsDataAccessException {returndao.getList();

}

}

11、 springMVC的控制器,AccountController代码如下:

packagecom.hoo.controller;importjavax.inject.Inject;importjavax.servlet.http.HttpServletRequest;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.ExceptionHandler;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.beans.factory.annotation.Autowired;importcom.hoo.biz.AccountBiz;importcom.hoo.entity.Account;importorg.springframework.beans.factory.annotation.Qualifier;

@Controller("accountController")

@RequestMapping("/account")publicclassAccountController {

@Autowired

@Qualifier("accountBizImpl")privateAccountBizbiz;

@RequestMapping("/add")publicString add(@RequestParam String username, @RequestParam String password, @RequestParam String status)

{

Integer stat=Integer.valueOf(status);

Account acc=newAccount(username,password,stat);

System.out.println(acc);

biz.addAccount(acc);return"redirect:/account/list.do";

}

@RequestMapping("/get")publicString get(Integer id,Model model)

{

System.out.println("###ID:"+id);

model.addAttribute(biz.getAccount(id));return"/show.jsp";

}

@RequestMapping("/list")publicString list(Model model)

{

model.addAttribute("list",biz.getList());return"/list.jsp";

}

@ExceptionHandler(Exception.class)publicString exception(Exception e,HttpServletRequest request)

{

request.setAttribute("exception", e);return"/error.jsp";

}

}

12、 基本页面代码

index.jsp

整合springmvc3.2+spring+mybatis3.2

查询所有
添加
查询

List.jsp

<%@ page language="java"import="java.util.*"pageEncoding="utf-8"%><%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%>My JSP 'list.jsp' starting page-->id:${data.accountId }--name:${data.username }--password:

${data.password }


show.jsp

${account }

${account.username }#${account.accountId }

error.jsp

Exception:${exception }

详细信息

<% Exception ex=(Exception)request.getAttribute("exception"); %>

<%ex.printStackTrace(new PrintWriter(out)); %>

13、 以上就基本上完成了整个Spring+SpringMVC+MyBatis的整合了。如果你想添加事务管理,得在applicationContext-common.xml中加入如下配置:


同时还需要加入aspectjweaver.jar这个jar包;

注意的是:Jdbc的TransactionManager不支持事务隔离级别,我在整个地方加入其它的TransactionManager,增加对transaction的隔离级别都尝试失败!

也许可以用于jpa、jdo、jta这方面的东西。

框架/平台构成:

Maven+Springmvc + Mybatis + Shiro(权限)+ Tiles(模板) +ActiveMQ(消息队列) + Rest(服务) + WebService(服务)+ EHcache(缓存) + Quartz(定时调度)+ Html5(支持PC、IOS、Android)

用户权限系统:

组织结构:角色、用户、用户组、组织机构;权限点:页面、方法、按钮、数据权限、分级授权

项目管理新体验:

快速出原型系统、组件树、版本控制、模块移植、协同开发、实时监控、发布管理

可持续集成:

所有组件可移植、可定制、可扩充,开发成果不断积累,形成可持续发展的良性循环

支持平台平台:

Windows XP、Windows 7 、Windows 10 、 Linux 、 Unix

服务器容器:

Tomcat 5/6/7 、Jetty、JBoss、WebSphere 8.5

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,924评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,902评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,716评论 0 239
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,783评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,166评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,510评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,784评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,476评论 0 196
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,196评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,459评论 2 243
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,978评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,321评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,964评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,046评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,803评论 0 193
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,530评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,420评论 2 265

推荐阅读更多精彩内容