MyBatis3整合Spring3、SpringMVC.pdf

上传人:索**** 文档编号:76195737 上传时间:2023-03-08 格式:PDF 页数:28 大小:399.52KB
返回 下载 相关 举报
MyBatis3整合Spring3、SpringMVC.pdf_第1页
第1页 / 共28页
MyBatis3整合Spring3、SpringMVC.pdf_第2页
第2页 / 共28页
点击查看更多>>
资源描述

《MyBatis3整合Spring3、SpringMVC.pdf》由会员分享,可在线阅读,更多相关《MyBatis3整合Spring3、SpringMVC.pdf(28页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。

1、MyBatis整合 Spring 开发环境:System:Windows WebBrowser:IE6+、Firefox3+JavaEE Server:tomcat5.0.2.8、tomcat6 IDE:eclipse、MyEclipse 8 Database:MySQL 开发依赖库:JavaEE5、Spring 3.0.5、Mybatis 3.0.4、myBatis-spring-1.0、junit4.8.2 Email:hoojo_ Blog:http:/ 命名为 MyBatisForSpring,新建项目时,使用 JavaEE5的 lib库。然后手动添加需要的jar包,所需jar包如下:

2、2、添加 spring的监听及springMVC的核心 Servlet,web.xml内容,内容如下:org.springframework.web.context.ContextLoaderListenercontextConfigLocationclasspath*:applicationContext-*.xmldispatcherorg.springframework.web.servlet.DispatcherServlet contextConfigLocation/WEB-INF/dispatcher.xml1dispatcher*.docharacterEncodingFilt

3、erorg.springframework.web.filter.CharacterEncodingFilterencodingUTF-8 characterEncodingFilter/*3、在 WEB-INF 目录中添加dispatcher.xml,内容如下:4、在 src目录下添加applicationContext-common.xml,内容如下:classpath:com/hoo/resultmap/*/*-resultmap.xmlclasspath:com/hoo/entity/*-resultmap.xmlclasspath:com/hoo/mapper/*/*-mapper.

4、xml!-上面的配置最先配置的是DataSource,这里采用的是jdbc的 DataSource;然后是 SqlSessionFactoryBean,这个配置比较关键。SqlSessionFactoryBean需要注入 DataSource数据源,其次还要设置configLocation也就是 mybatis的xml 配置文件路径,完成一些关于mybatis的配置,如 settings、mappers、plugin等;如 果使 用mapperCannerConfigurer模式,需 要设 置扫 描根 路径 也就 是你 的mybatis的 mapper接口所在包路径;凡是 markerInte

5、rface这个接口的子接口都参与到这个扫描,也就是说所有的mapper接口继承这个SqlMapper。如果你不使用自己的transaction事务,就使用MapperScannerConfigurer来完成 SqlSession的打开、关闭和事务的回滚操作。在此期间,出现数据库操作的如何异常都会被转换成DataAccessException,这个异常是一个抽象的类,继承RuntimeException;5、SqlMapper内容如下:package com.hoo.mapper;/*function:所有的 Mapper 继承这个接口*author hoojo*createDate 2011-

6、4-12 下午 04:00:31*file SqlMapper.java*package com.hoo.mapper*project MyBatisForSpring*blog http:/ hoojo_*version 1.0*/publicinterface SqlMapper 6、实体类和 ResultMap.xml package com.hoo.entity;import java.io.Serializable;import javax.persistence.Entity;Entitypublicclass Account implements Serializable pri

7、vatestaticfinallongserialVersionUID=-7970848646314840509L;private Integer accountId;private Integer status;private String username;private String password;private String salt;private String email;private Integer roleId;/getter、setter Overridepublic String toString()returnthis.accountId+#+this.status

8、+#+this.username+#+this.password+#+this.email+#+this.salt+#+this.roleId;account-resultmap.xml 7、在 src目录中添加applicationContext-beans.xml内容如下:这里配置 bean 对象,一些不能用annotation注解的对象就可以配置在这里8、在 src目录中添加mybatis.xml,内容如下:在这个文件放置一些全局性的配置,如handler、objectFactory、plugin、以及mappers的 映 射 路 径(由 于 在applicationContext-co

9、mmon中 的SqlSessionFactoryBean有配置 mapper的 location,这里就不需要配置)等9、AccountMapper接口,内容如下:package com.hoo.mapper;import java.util.List;import org.apache.ibatis.annotations.Select;import com.hoo.entity.Account;/*function:继承 SqlMapper,MyBatis数据操作接口;此接口无需实现类*author hoojo*createDate 2010-12-21 下午 05:21:20*file

10、AccountMapper.java*package com.hoo.mapper*project MyBatis*blog http:/ hoojo_*version 1.0*/publicinterface AccountMapper extends SqlMapper public List getAllAccount();public Account getAccount();public Account getAccountById(String id);public Account getAccountByNames(String spring);Select(select*fro

11、m account where username=#name)public Account getAccountByName(String name);publicvoid addAccount(Account account);publicvoid editAccount(Account account);publicvoid removeAccount(int id);这个接口我们不需要实现,由 mybatis帮助我们实现,我们通过mapper文件配置sql语句即可完成接口的实现。然后这个接口需要继承SqlMapper接口,不然在其他地方就不能从 Spring容器中拿到这个mapper接口

12、,也就是说当我们注入这个接口的时候将会失败。当然,你不继承这个接口也可以。那就是你需要给买个mapper配置一个bean。配置方法如下:这里的 MapperFactoryBean可以帮助我们完成Session的打开、关闭等操作10、在com.hoo.mapper也就是在AccountMapper接口的同一个包下,添加account-mapper.xml,内容如下:username,password insert into account(account_id,status,username,password)values(#accountId,#status,#username,#passwo

13、rd)select cast(random()*10000 as Integer)a from#Tab insert 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 上面的 n

14、amespace和定义接口类路径对应,所有的 sql语句,如 select、insert、delete、update的 id和方法名称对应。关于更多MyBatis内容的讲解,这里就不赘述的。这里只完成整合!如果你不懂可以去阅读其他关于MyBatis的资料。11、为了测试发布,这里使用 junit和 spring官方提供的spring-test.jar,完成 spring框架整合的测试,代码如下:package com.hoo.mapper;import java.util.List;import javax.inject.Inject;import org.springframework.te

15、st.context.ContextConfiguration;importorg.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;import com.hoo.entity.Account;/*function:AccountMapper JUnit测试类*author hoojo*createDate 2011-4-12 下午 04:21:50*file AccountMapperTest.java*package com.hoo.mapper*project MyBatisForSpring*b

16、log http:/ hoojo_*version 1.0*/ContextConfiguration(classpath:applicationContext-*.xml)publicclass AccountMapperTest extendsAbstractJUnit38SpringContextTests Inject/Named(accountMapper)private AccountMapper mapper;publicvoid testGetAccount()System.out.println(mapper.getAccount();publicvoid testGetAc

17、countById()System.out.println(mapper.getAccountById(28);publicvoid testGetAccountByName()System.out.println(mapper.getAccountByName(user);publicvoid testGetAccountByNames()System.out.println(mapper.getAccountByNames(user);publicvoid testAdd()Account account=new Account();account.setEmail();account.s

18、etPassword(abc);account.setRoleId(1);account.setSalt(ss);account.setStatus(0);account.setUsername(Jack);mapper.addAccount(account);publicvoid testEditAccount()Account acc=mapper.getAccountByNames(Jack);System.out.println(acc);acc.setUsername(Zhangsan);acc.setPassword(123123);mapper.editAccount(acc);

19、System.out.println(mapper.getAccountById(acc.getAccountId()+);publicvoid testRemoveAccount()Account acc=mapper.getAccountByNames(Jack);mapper.removeAccount(acc.getAccountId();System.out.println(mapper.getAccountByNames(Jack);publicvoid testAccountList()List acc=mapper.getAllAccount();System.out.prin

20、tln(acc.size();System.out.println(acc);这里的注入并没有使用Autowired、Resource、Qualifier注入,而是使用Inject、Named注入方式,Inject注入是 JSR330的标准注入方式;而不局限于某个产品,使用于多个产品的使用,推荐使用这种方式;运行后,没有发现问题,就可以继续后续的编码工作了。12、定义 AccountDao接口及实现代码,代码如下:package com.hoo.dao;import java.util.List;import org.springframework.dao.DataAccessExceptio

21、n;/*function:Account数据库操作 dao 接口*author hoojo*createDate 2011-4-13 上午 10:21:38*file AccountDao.java*package com.hoo.dao*project MyBatisForSpring*blog http:/ hoojo_*version 1.0*/publicinterface AccountDao /*function:添加 Account对象信息*author hoojo*createDate 2011-4-13 上午 11:50:05*param entity Account*ret

22、urn boolean 是否成功*throws DataAccessException*/publicboolean addAccount(T entity)throws DataAccessException;/*function:根据 id 对到 Account信息*author hoojo*createDate 2011-4-13 上午 11:50:45*param id 编号 id*return Account*throws DataAccessException*/public T getAccount(Integer id)throws DataAccessException;/*

23、function:查询所有 Account信息*author hoojo*createDate 2011-4-13 上午 11:51:45*param id 编号 id*return Account*throws DataAccessException*/public List getList()throws DataAccessException;接口实现package com.hoo.dao.impl;import java.util.List;import javax.inject.Inject;import org.springframework.dao.DataAccessExcep

24、tion;import org.springframework.stereotype.Repository;import com.hoo.dao.AccountDao;import com.hoo.entity.Account;import com.hoo.mapper.AccountMapper;/*function:Account数据库操作 dao*author hoojo*createDate 2011-4-13 上午 10:25:02*file AccountDaoImpl.java*package com.hoo.dao.impl*project MyBatisForSpring*b

25、log http:/ hoojo_*version 1.0*/SuppressWarnings(unchecked)Repositorypublicclass AccountDaoImpl implementsAccountDao Injectprivate AccountMapper mapper;publicbooleanaddAccount(T entity)throwsDataAccessException boolean flag=false;try mapper.addAccount(entity);flag=true;catch(DataAccessException e)fla

26、g=false;throw e;return flag;public T getAccount(Integer id)throws DataAccessException T entity=null;try entity=(T)mapper.getAccountById(String.valueOf(id);catch(DataAccessException e)throw e;return entity;public List getList()throws DataAccessException return(List)mapper.getAllAccount();13、服务层 Accou

27、ntBiz接口及实现代码接口:package com.hoo.biz;import java.util.List;import org.springframework.dao.DataAccessException;/*function:biz层Account接口*author hoojo*createDate 2011-4-13 上午 11:33:04*file AccountBiz.java*package com.hoo.biz*project MyBatisForSpring*blog http:/ hoojo_*version 1.0*/publicinterface Account

28、Biz /*function:添加 Account对象信息*author hoojo*createDate 2011-4-13 上午 11:50:05*param entity Account*return boolean 是否成功*throws DataAccessException*/publicboolean addAccount(T entity)throws DataAccessException;/*function:根据 id 对到 Account信息*author hoojo*createDate 2011-4-13 上午 11:50:45*param id 编号 id*ret

29、urn Account*throws DataAccessException*/public T getAccount(Integer id)throws DataAccessException;/*function:查询所有 Account信息*author hoojo*createDate 2011-4-13 上午 11:51:45*param id 编号 id*return Account*throws DataAccessException*/public List getList()throws DataAccessException;实现代码:package com.hoo.biz

30、.impl;import java.util.List;import javax.inject.Inject;import org.springframework.dao.DataAccessException;import org.springframework.stereotype.Service;import com.hoo.biz.AccountBiz;import com.hoo.dao.AccountDao;import com.hoo.entity.Account;import com.hoo.exception.BizException;/*function:Account B

31、iz接口实现*author hoojo*createDate 2011-4-13 上午 11:34:39*file AccountBizImpl.java*package com.hoo.biz.impl*project MyBatisForSpring*blog http:/ hoojo_*version 1.0*/ComponentServicepublicclass AccountBizImpl implementsAccountBiz Injectprivate AccountDao dao;publicbooleanaddAccount(T entity)throwsDataAcce

32、ssException if(entity=null)thrownew BizException(Account.class.getName()+对象参数信息为 Empty!);returndao.addAccount(entity);public T getAccount(Integer id)throws DataAccessException returndao.getAccount(id);public List getList()throws DataAccessException returndao.getList();上面用到了一个自定义的异常信息,代码如下:package co

33、m.hoo.exception;import org.springframework.dao.DataAccessException;/*function:自定义 Biz 层异常信息*author hoojo*createDate 2011-4-13 上午 11:42:19*file BizException.java*package com.hoo.exception*project MyBatisForSpring*blog http:/ hoojo_*version 1.0*/publicclass BizException extends DataAccessException /*a

34、uthor Hoojo*/privatestaticfinallongserialVersionUID=1L;public BizException(String msg)super(msg);public BizException(String msg,Throwable cause)super(msg,cause);这里只是简单的继承,如果还有其他的异常业务或需求可以进行具体的实现14、springMVC的控制器,AccountController代码如下:package com.hoo.controller;import javax.inject.Inject;import javax.

35、servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RequestMapping;import com.hoo.biz.AccountBiz;import com.hoo.entity.Accou

36、nt;/*function:Account控制器*author hoojo*createDate 2011-4-13 上午 10:18:02*file AccountController.java*package com.hoo.controller*project MyBatisForSpring*blog http:/ hoojo_*version 1.0*/ControllerRequestMapping(/account)publicclass AccountController Injectprivate AccountBiz biz;RequestMapping(/add)publ

37、ic String add(Account acc)System.out.println(acc);biz.addAccount(acc);returnredirect:/account/list.do;RequestMapping(/get)public String get(Integer id,Model model)System.out.println(#ID:+id);model.addAttribute(biz.getAccount(id);return/show.jsp;RequestMapping(/list)public String list(Model model)mod

38、el.addAttribute(list,biz.getList();return/list.jsp;ExceptionHandler(Exception.class)publicString exception(Exception e,HttpServletRequest request)/e.printStackTrace();request.setAttribute(exception,e);return/error.jsp;15、基本页面代码index.jsp basehref=MyBatis 整合 Spring 3.0.5MyBatis 3.0.4 整合 Spring 3.0.5查询

39、所有 添加查询 List.jsp basehref=all Account Resultid:$data.accountId-name:$data.username-password:$data.password show.jsp basehref=show Account$account$account.username#$account.accountId error.jsp basehref=Error PageException:$exception 详细信息16、以上就基本上完成了整个Spring+SpringMVC+MyBatis的整合了。如果你想添加事务管理,得在applicat

40、ionContext-common.xml中加入如下配置:同时还需要加入aspectjweaver.jar这个 jar包;注意的是:Jdbc的 TransactionManager不支持事务隔离级别,我在整个地方加入其它的 TransactionManager,增加对transaction的隔离级别都尝试失败!也许可以用于jpa、jdo、jta这方面的东西。不知道大家对MyBatis的事务是怎么处理的?17、对 Dao 进行扩展封装,运用SqlSessionDaoSupport进行模板的扩展或运用:BaseDao代码如下:package com.hoo.dao.impl;import java

41、.util.ArrayList;import java.util.List;import javax.inject.Inject;import org.apache.ibatis.session.SqlSessionFactory;import org.mybatis.spring.support.SqlSessionDaoSupport;import org.springframework.stereotype.Repository;import com.hoo.dao.BaseDao;/*function:运用 SqlSessionDaoSupport封装 Dao 常用增删改方法,可以进行

42、扩展*author hoojo*createDate 2011-4-13 下午 06:33:37*file BaseDaoImpl.java*package com.hoo.dao.impl*project MyBatisForSpring*blog http:/ hoojo_*version 1.0*/RepositorySuppressWarnings(unchecked,unused)publicclass BaseDaoImpl extendsSqlSessionDaoSupport implements BaseDao Injectprivate SqlSessionFactory

43、sqlSessionFactory;publicbooleanadd(String classMethod,T entity)throwsException boolean flag=false;try flag=this.getSqlSession().insert(classMethod,entity)0?true:false;catch(Exception e)flag=false;throw e;return flag;publicbooleanedit(String classMethod,T entity)throwsException boolean flag=false;try

44、 flag=this.getSqlSession().update(classMethod,entity)0?true:false;catch(Exception e)flag=false;throw e;return flag;public T get(String classMethod,T entity)throws Exception T result=null;try result=(T)this.getSqlSession().selectOne(classMethod,entity);catch(Exception e)throw e;return result;public L

45、ist getAll(String classMethod)throws Exception List result=new ArrayList();try result=this.getSqlSession().selectList(classMethod);catch(Exception e)throw e;return result;publicboolean remove(String classMethod,T entity)throwsException boolean flag=false;try flag=this.getSqlSession().delete(classMet

46、hod,entity)0?true:false;catch(Exception e)flag=false;throw e;return flag;值得说明的是,这个类继承了SqlSessionDaoSupport,它需要我们帮助它注入SqlSessionFactory或 是SqlSessionTemplate,如果两者都被注入将忽略SqlSessionFactory属性,使用SqlSessionTemplate模板。继承 SqlSessionDaoSupport后,可以拿到SqlSession完成数据库的操作;18、对 Dao 进行扩展封装,运用SqlSessionTemplate进行模板的扩

47、展或运用:首先看看这个组件中运用的一个Mapper的基类接口:package com.hoo.mapper;import java.util.List;import org.springframework.dao.DataAccessException;/*function:BaseSqlMapper继承 SqlMapper,对 Mapper 进行接口封装,提供常用的增删改查组件;*也可以对该接口进行扩展和封装*author hoojo*createDate 2011-4-14 上午 11:36:41*file BaseSqlMapper.java*package com.hoo.mapper

48、*project MyBatisForSpring*blog http:/ hoojo_*version 1.0*/publicinterface BaseSqlMapper extends SqlMapper publicvoid add(T entity)throws DataAccessException;publicvoid edit(T entity)throws DataAccessException;publicvoid remvoe(T entity)throws DataAccessException;public T get(T entity)throws DataAcce

49、ssException;public List getList(T entity)throws DataAccessException;该接口继承SqlMapper接口,但是该接口没有MyBatis的 mapper实现。需要我们自己的业务mapper继承这个接口,完成上面的方法的实现。看看继承 SqlSessionTemplate的 BaseMapperDao代码:package com.hoo.dao.impl;import java.util.List;import javax.inject.Inject;import org.apache.ibatis.session.SqlSessio

50、nFactory;import org.mybatis.spring.SqlSessionTemplate;import org.springframework.stereotype.Repository;import com.hoo.dao.BaseMapperDao;import com.hoo.mapper.BaseSqlMapper;/*function:运用 SqlSessionTemplate封装 Dao 常用增删改方法,可以进行扩展*author hoojo*createDate 2011-4-14 下午 12:22:07*file BaseMapperDaoImpl.java*

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 技术资料 > 技术方案

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知得利文库网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号-8 |  经营许可证:黑B2-20190332号 |   黑公网安备:91230400333293403D

© 2020-2023 www.deliwenku.com 得利文库. All Rights Reserved 黑龙江转换宝科技有限公司 

黑龙江省互联网违法和不良信息举报
举报电话:0468-3380021 邮箱:hgswwxb@163.com