MyBatis集成Spring流程详解

目录

  • 一、Mybatis与spring集成
    • 1. 导入pom依赖
    • 2. 编写配置文件
    • 3. 使用注解开发
    • 4. 测试
    • 5. 管理数据源
  • 二、Aop整合pagehelper插件
    • 要解决的问题

一、Mybatis与spring集成
1. 导入pom依赖
UTF-81.81.83.7.05.0.2.RELEASE3.4.55.1.445.1.21.3.12.1.12.4.32.9.14.124.0.01.18.2org.springframeworkspring-context${spring.version}org.springframeworkspring-orm${spring.version}org.springframeworkspring-tx${spring.version}org.springframeworkspring-aspects${spring.version}org.springframeworkspring-web${spring.version}org.springframeworkspring-test${spring.version}org.mybatismybatis${mybatis.version}mysqlmysql-connector-java${mysql.version}com.github.pagehelperpagehelper${pagehelper.version}org.mybatismybatis-spring${mybatis.spring.version}org.apache.commonscommons-dbcp2${commons.dbcp2.version}org.apache.commonscommons-pool2${commons.pool2.version}org.apache.logging.log4jlog4j-core${log4j2.version}org.apache.logging.log4jlog4j-api${log4j2.version}org.apache.logging.log4jlog4j-web${log4j2.version}junitjunit${junit.version}testjavax.servletjavax.servlet-api${servlet.version}providedorg.projectlomboklombok${lombok.version}providedsrc/main/java**/*.xmlsrc/main/resourcesjdbc.properties*.xmlorg.apache.maven.pluginsmaven-compiler-plugin${maven.compiler.plugin.version}${maven.compiler.source}${maven.compiler.target}${project.build.sourceEncoding}org.mybatis.generatormybatis-generator-maven-plugin1.3.2mysqlmysql-connector-java${mysql.version}true


2. 编写配置文件
applicationContext-mybatis.xml
helperDialect=mysql


3. 使用注解开发
@Repository:将DAO类声明为Bean
@Service:通常作用在业务层
@Constroller:通常作用在控制层,将在Spring MVC中使用
@Component:是一个泛化的概念,仅仅表示spring中的一个组件(Bean),可以作用在任何层次
@Scope:模式声明(singleton|prototype)
@Autowired:将自动在代码上下文与其匹配(默认是类型匹配)的Bean,并自动注入到相应的地方

4. 测试
我们就可以把BookBizImpl实现类里面添加两个注解,相当于省略了set、get方法
package com.xlb.biz.impl; import com.xlb.biz.BookBiz; import com.xlb.mapper.BookMapper; import com.xlb.model.Book; import com.xlb.model.BookVo; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Servicepublic class BookBizImpl implements BookBiz {@Autowiredprivate BookMapper bookMapper; //Alt+Enter 快速构建实现类,填充代码的前半部分 Ctrl+1//Alt+Insert 快速提供set/get/toString/构造方法/*public BookMapper getBookMapper() {return bookMapper; }public void setBookMapper(BookMapper bookMapper) {this.bookMapper = bookMapper; }*/@Overridepublic int deleteByPrimaryKey(Integer bid) {return bookMapper.deleteByPrimaryKey(bid); }@Overridepublic Book selectByPrimaryKey(Integer bid) {return bookMapper.selectByPrimaryKey(bid); }@Overridepublic List selectByIn(List bookIds) {return bookMapper.selectByIn(bookIds); }public List selectBooksLike1(String bname){returnbookMapper.selectBooksLike1(bname); }public List selectBooksLike2(String bname){returnbookMapper.selectBooksLike2(bname); }public List selectBooksLike3(String bname){returnbookMapper.selectBooksLike3(bname); }@Overridepublic List list1() {return bookMapper.list1(); }@Overridepublic List list2() {return bookMapper.list2(); }@Overridepublic List list3(BookVo vo) {return bookMapper.list3(vo); }@Overridepublic List list4() {return bookMapper.list4(); }@Overridepublic Map list5(Map map) {return bookMapper.list5(map); }@Overridepublic List list6(BookVo bookVo) {return bookMapper.list6(bookVo); }@Overridepublic List list7(BookVo bookVo) {return list7(bookVo); }}


5. 管理数据源
管理sqlsession
我们还要给BookMapper.java添加一个标记:
MyBatis集成Spring流程详解
文章图片

然后在测试类里面添加:
@RunWith(SpringJUnit4ClassRunner.class)
【MyBatis集成Spring流程详解】@ContextConfiguration(locations={“classpath:applicationContext-mybatis.xml”})
package com.xlb.biz.impl; import com.xlb.biz.BookBiz; import com.xlb.mapper.BookMapper; import com.xlb.model.BookVo; import com.xlb.util.SessionUtil; import com.xlb.biz.impl.BookBizImpl; import org.apache.ibatis.session.SqlSession; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={"classpath:applicationContext-mybatis.xml"})public class BookBizImplTest {private BookBiz bookBiz; private SqlSession sqlSession; @Beforepublic void setUp() throws Exception {System.out.println("初始化方法..."); BookBizImpl bookBiz = new BookBizImpl(); //工具类中获取session对象sqlSession = SessionUtil.openSession(); System.out.println(sqlSession+"初始化方法"); //从session对象中获取mapper对象BookMapper mapper = sqlSession.getMapper(BookMapper.class); bookBiz.setBookMapper(mapper); this.bookBiz = bookBiz; }@Afterpublic void tearDown() throws Exception {System.out.println("方法测试结束..."); System.out.println(sqlSession); sqlSession.commit(); sqlSession.close(); }@Testpublic void deleteByPrimaryKey() {bookBiz.deleteByPrimaryKey(44); sqlSession.commit(); sqlSession.close(); }@Testpublic void selectByPrimaryKey() {System.out.println("测试的业务方法..."); System.out.println(bookBiz.selectByPrimaryKey(44)); }@Testpublic void text3() {int[] ints = {1,2,3,4}; //将数组变为字符串StringBuffer sb = new StringBuffer(); for (int i : ints){sb.append(",").append(i); }String s = sb.toString(); System.out.println(s.substring(1)); }@Testpublic void selectByIn() {List integers = Arrays.asList(new Integer[] {33,34,32}); bookBiz.selectByIn(integers).forEach(System.out::println); }@Testpublic void selectBooksLike1() {bookBiz.selectBooksLike1("%圣嘘%").forEach(System.out::println); }@Testpublic void selectBooksLike2() {bookBiz.selectBooksLike2("%圣嘘%").forEach(System.out::println); }@Testpublic void selectBooksLike3() {bookBiz.selectBooksLike3("圣嘘").forEach(System.out::println); }@Testpublic void list1() {bookBiz.list1().forEach(System.out::println); }@Testpublic void list2() {bookBiz.list2().forEach(System.out::println); }@Testpublic void list3() {BookVo vo = new BookVo(); vo.setBooKIds(Arrays.asList(new Integer[]{31,32,33,34})); bookBiz.list3(vo).forEach(System.out::println); }@Testpublic void list4() {bookBiz.list4().forEach(System.out::println); }@Testpublic void list5() {Map map = new HashMap(); map.put("bid",32); System.out.println(bookBiz.list5(map)); }@Testpublic void list6() {BookVo vo = new BookVo(); vo.setMax(45); vo.setMin(35); bookBiz.list6(vo).forEach(System.out::println); }@Testpublic void list7() {BookVo vo = new BookVo(); vo.setMax(45); vo.setMin(35); bookBiz.list7(vo).forEach(System.out::println); }}

结果
MyBatis集成Spring流程详解
文章图片


二、Aop整合pagehelper插件
要解决的问题
@Overridepublic List listPager(Map map, PageBean pageBean) {//pageHelper分页插件相关代码if(pageBean != null && pageBean.isPagination()){PageHelper.startPage(pageBean.getPage(),pageBean.getRows()); }List maps=bookMapper.listPager(map,pageBean); if(pageBean != null && pageBean.isPagination()){//处理查询结果的前提,是需要分页的PageInfo info=new PageInfo(maps); pageBean.setTotal(info.getTotal()+""); }return maps; }

可以使用AOP编程解决分页代码重复的问题,省掉重复的代码。
根据Spring aop所学,我们可以利用环绕通知来解决;
1、找到目标对象 -> *Biz.*Pager
2、写通知
目标对象该方法一定携带了PageBean对象
注解:@aspect:相当于配置了环绕通知
@component:交给Spring进行管理
@excution
建立一个切面类:PageAspect
package com.xlb.ssm.aspect; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.xlb.ssm.entity.PageBean; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; import java.util.List; @Component@Aspectpublic class PageAspect {/*** *:返回值* *..:无限包* *Service:以Service结尾的接口名* .Pager:以Pager方法* 只要同时匹配上诉四个条件,就会被列为目标对象* 上诉配置要生效,代理注释一定要打开:* @param args* @return* @throws Throwable*/@Around("execution(* *..*Biz.*Pager(..))")public Object invoke(ProceedingJoinPoint args) throws Throwable {Object[] params = args.getArgs(); PageBean pageBean = null; for (Object param : params) {if(param instanceof PageBean){pageBean = (PageBean)param; break; }}if(pageBean != null && pageBean.isPagination())PageHelper.startPage(pageBean.getPage(),pageBean.getRows()); Object list = args.proceed(params); if(null != pageBean && pageBean.isPagination()){PageInfo pageInfo = new PageInfo((List) list); pageBean.setTotal(pageInfo.getTotal()+""); }return list; }}

@Around:代表这是一个环绕通知
测试一下
@Testpublic void listPager() {Map map=new HashMap(); map.put("bname","圣墟"); //查询出第二页的20条数据PageBean pageBean=new PageBean(); pageBean.setPage(2); pageBean.setRows(20); bookBiz.listPager(map,pageBean).forEach(System.out::println); }

结果:
MyBatis集成Spring流程详解
文章图片

到此这篇关于MyBatis集成Spring流程详解的文章就介绍到这了,更多相关MyBatis集成Spring内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读