java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > MyBatis集成Spring

MyBatis集成Spring流程详解

作者:小谢同学189

在实际开发中不仅仅是要展示数据,还要构成数据模型添加数据,这篇文章主要介绍了SpringBoot集成Mybatis操作数据库,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、Mybatis与spring集成

1. 导入pom依赖

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>
    <!--添加jar包依赖-->
    <!--1.spring 5.0.2.RELEASE相关-->
    <spring.version>5.0.2.RELEASE</spring.version>
    <!--2.mybatis相关-->
    <mybatis.version>3.4.5</mybatis.version>
    <!--mysql-->
    <mysql.version>5.1.44</mysql.version>
    <!--pagehelper分页jar依赖-->
    <pagehelper.version>5.1.2</pagehelper.version>
    <!--mybatis与spring集成jar依赖-->
    <mybatis.spring.version>1.3.1</mybatis.spring.version>
    <!--3.dbcp2连接池相关 druid-->
    <commons.dbcp2.version>2.1.1</commons.dbcp2.version>
    <commons.pool2.version>2.4.3</commons.pool2.version>
    <!--4.log日志相关-->
    <log4j2.version>2.9.1</log4j2.version>
    <!--5.其他-->
    <junit.version>4.12</junit.version>
    <servlet.version>4.0.0</servlet.version>
    <lombok.version>1.18.2</lombok.version>
</properties>
<dependencies>
    <!--1.spring相关-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!--2.mybatis相关-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
    </dependency>
    <!--mysql-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.version}</version>
    </dependency>
    <!--pagehelper分页插件jar包依赖-->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>${pagehelper.version}</version>
    </dependency>
    <!--mybatis与spring集成jar包依赖-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>${mybatis.spring.version}</version>
    </dependency>
    <!--3.dbcp2连接池相关-->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>${commons.dbcp2.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
        <version>${commons.pool2.version}</version>
    </dependency>
    <!--4.log日志相关依赖-->
    <!--核心log4j2jar包-->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>${log4j2.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>${log4j2.version}</version>
    </dependency>
    <!--web工程需要包含log4j-web,非web工程不需要-->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-web</artifactId>
        <version>${log4j2.version}</version>
    </dependency>
    <!--5.其他-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${servlet.version}</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombok.version}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
<resources>
    <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
    <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>jdbc.properties</include>
            <include>*.xml</include>
        </includes>
    </resource>
</resources>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${maven.compiler.plugin.version}</version>
    <configuration>
        <source>${maven.compiler.source}</source>
        <target>${maven.compiler.target}</target>
        <encoding>${project.build.sourceEncoding}</encoding>
    </configuration>
</plugin>
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.2</version>
    <dependencies>
        <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
    </dependencies>
    <configuration>
        <overwrite>true</overwrite>
    </configuration>
</plugin>

2. 编写配置文件

applicationContext-mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--1. 注解式开发 -->
    <!-- 注解驱动 -->
    <context:annotation-config/>
    <!-- 用注解方式注入bean,并指定查找范围:com.javaxl.ssm及子子孙孙包-->
    <context:component-scan base-package="com.xlb"/>
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!--初始连接数-->
        <property name="initialSize" value="10"/>
        <!--最大活动连接数-->
        <property name="maxTotal" value="100"/>
        <!--最大空闲连接数-->
        <property name="maxIdle" value="50"/>
        <!--最小空闲连接数-->
        <property name="minIdle" value="10"/>
        <!--设置为-1时,如果没有可用连接,连接池会一直无限期等待,直到获取到连接为止。-->
        <!--如果设置为N(毫秒),则连接池会等待N毫秒,等待不到,则抛出异常-->
        <property name="maxWaitMillis" value="-1"/>
    </bean>
    <!--4. spring和MyBatis整合 -->
    <!--1) 创建sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 自动扫描XxxMapping.xml文件,**任意路径 -->
        <property name="mapperLocations" value="classpath*:com/xlb/**/mapper/*.xml"/>
        <!-- 指定别名 -->
        <property name="typeAliasesPackage" value="com/javaxl/ssm/**/model"/>
        <!--配置pagehelper插件-->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>
    <!--2) 自动扫描com/javaxl/ssm/**/mapper下的所有XxxMapper接口(其实就是DAO接口),并实现这些接口,-->
    <!--   即可直接在程序中使用dao接口,不用再获取sqlsession对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--basePackage 属性是映射器接口文件的包路径。-->
        <!--你可以使用分号或逗号 作为分隔符设置多于一个的包路径-->
        <property name="basePackage" value="com/javaxl/ssm/**/mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />
    <aop:aspectj-autoproxy/>
</beans>

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;
@Service
public class BookBizImpl implements BookBiz {
    @Autowired
    private BookMapper bookMapper;
    //Alt+Enter 快速构建实现类,填充代码的前半部分 Ctrl+1
    //Alt+Insert 快速提供set/get/toString/构造方法

    /*public BookMapper getBookMapper() {
        return bookMapper;
    }
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }*/
    @Override
    public int deleteByPrimaryKey(Integer bid) {
        return bookMapper.deleteByPrimaryKey(bid);
    }
    @Override
    public Book selectByPrimaryKey(Integer bid) {
        return bookMapper.selectByPrimaryKey(bid);
    }
    @Override
    public List<Book> selectByIn(List bookIds) {
        return bookMapper.selectByIn(bookIds);
    }
    public List<Book> selectBooksLike1(String bname){
        return  bookMapper.selectBooksLike1(bname);
    }
    public List<Book> selectBooksLike2(String bname){
        return  bookMapper.
    selectBooksLike2(bname);
}
    public List<Book> selectBooksLike3(String bname){
        return  bookMapper.selectBooksLike3(bname);
    }
    @Override
    public List<Book> list1() {
        return bookMapper.list1();
    }
    @Override
    public List<Book> list2() {
        return bookMapper.list2();
    }
    @Override
    public List<Book> list3(BookVo vo) {
        return bookMapper.list3(vo);
    }
    @Override
    public List<Map> list4() {
        return bookMapper.list4();
    }
    @Override
    public Map list5(Map map) {
        return bookMapper.list5(map);
    }
    @Override
    public List<Book> list6(BookVo bookVo) {
        return bookMapper.list6(bookVo);
    }
    @Override
    public List<Book> list7(BookVo bookVo) {
        return list7(bookVo);
    }
}

5. 管理数据源

管理sqlsession

我们还要给BookMapper.java添加一个标记:

然后在测试类里面添加:

@RunWith(SpringJUnit4ClassRunner.class)

@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;
    @Before
    public 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;
    }
    @After
    public void tearDown() throws Exception {
        System.out.println("方法测试结束...");
        System.out.println(sqlSession);
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void deleteByPrimaryKey() {
        bookBiz.deleteByPrimaryKey(44);
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void selectByPrimaryKey() {
        System.out.println("测试的业务方法...");
        System.out.println(bookBiz.selectByPrimaryKey(44));
    }
    @Test
    public 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));
    }
    @Test
    public void selectByIn() {
        List<Integer> integers = Arrays.asList(new Integer[] {33,34,32});
        bookBiz.selectByIn(integers).forEach(System.out::println);
    }
    @Test
    public void selectBooksLike1() {
        bookBiz.selectBooksLike1("%圣嘘%").forEach(System.out::println);
    }
    @Test
    public void selectBooksLike2() {
        bookBiz.selectBooksLike2("%圣嘘%").forEach(System.out::println);
    }
    @Test
    public void selectBooksLike3() {
        bookBiz.selectBooksLike3("圣嘘").forEach(System.out::println);
    }
    @Test
    public void list1() {
        bookBiz.list1().forEach(System.out::println);
    }
    @Test
    public void list2() {
        bookBiz.list2().forEach(System.out::println);
    }
    @Test
    public void list3() {
        BookVo vo = new BookVo();
        vo.setBooKIds(Arrays.asList(new Integer[]{31,32,33,34}));
        bookBiz.list3(vo).forEach(System.out::println);
    }
    @Test
    public void list4() {
        bookBiz.list4().forEach(System.out::println);
    }
    @Test
    public void list5() {
        Map map = new HashMap();
        map.put("bid",32);
        System.out.println(bookBiz.list5(map));
    }
    @Test
    public void list6() {
        BookVo vo = new BookVo();
        vo.setMax(45);
        vo.setMin(35);
        bookBiz.list6(vo).forEach(System.out::println);
    }
    @Test
    public void list7() {
        BookVo vo = new BookVo();
        vo.setMax(45);
        vo.setMin(35);
        bookBiz.list7(vo).forEach(System.out::println);
    }
}

结果

二、Aop整合pagehelper插件

要解决的问题

  @Override
    public List<Map> listPager(Map map, PageBean pageBean) {
        //pageHelper分页插件相关代码
        if(pageBean != null && pageBean.isPagination()){
            PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
        }
        List<Map> 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
@Aspect
public class PageAspect {
    /**
     * *:返回值
     * *..:无限包
     * *Service:以Service结尾的接口名
     * .Pager:以Pager方法
     * 只要同时匹配上诉四个条件,就会被列为目标对象
     * 上诉配置要生效,代理注释一定要打开:<aop:aspectj-autoproxy/>
     * @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:代表这是一个环绕通知

测试一下

    @Test
    public 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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文