• Mybatis与spring集成


    1、Mybatisspring集成

     2、Aop整合pagehelper插件

     Mybatisspring集成

     1、导入pom依赖

     1.1 添加spring相关依赖(5.0.2.RELEASE)

            spring-core

            spring-beans

            spring-context

            spring-orm

            spring-tx

            spring-aspects

            spring-web

         1.2 添加mybatis相关依赖

            mybatis核心:mybatis(3.4.5)

            Mybatis分页:pagehelper(5.1.2)

         1.3 spring整合mybatis(1.3.1)

            mybatis-spring

         1.4 添加dbcp2连接池

            commons-dbcp2(2.1.1)

            commons-pool2(2.4.3)

         1.5 添加日志配置(2.9.1)

            log4j-core

            log4j-api

            log4j-web

         1.6 其他

            junit(4.12)

            javax.servlet-api(4.0.0)

            lombok(1.18.2)

      1 <?xml version="1.0" encoding="UTF-8"?>
      2 
      3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      4   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      5   <modelVersion>4.0.0</modelVersion>
      6 
      7   <groupId>com.MavenMybatis</groupId>
      8   <artifactId>Mybatis_1</artifactId>
      9   <version>1.0-SNAPSHOT</version>
     10   <packaging>war</packaging>
     11   <name>ssm Maven Webapp</name>
     12   <!-- FIXME change it to the project's website -->
     13   <url>http://www.example.com</url>
     14 
     15   <properties>
     16     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     17     <maven.compiler.source>1.8</maven.compiler.source>
     18     <maven.compiler.target>1.8</maven.compiler.target>
     19     <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>
     20 
     21     <!--添加jar包依赖-->
     22     <!--1.spring 5.0.2.RELEASE相关-->
     23     <spring.version>5.0.2.RELEASE</spring.version>
     24     <!--2.mybatis相关-->
     25     <mybatis.version>3.4.5</mybatis.version>
     26     <!--mysql-->
     27     <mysql.version>5.1.44</mysql.version>
     28     <!--pagehelper分页jar依赖-->
     29     <pagehelper.version>5.1.2</pagehelper.version>
     30     <!--mybatis与spring集成jar依赖-->
     31     <mybatis.spring.version>1.3.1</mybatis.spring.version>
     32     <!--3.dbcp2连接池相关 druid-->
     33     <commons.dbcp2.version>2.1.1</commons.dbcp2.version>
     34     <commons.pool2.version>2.4.3</commons.pool2.version>
     35     <!--4.log日志相关-->
     36     <log4j2.version>2.9.1</log4j2.version>
     37     <!--5.其他-->
     38     <junit.version>4.12</junit.version>
     39     <servlet.version>4.0.0</servlet.version>
     40     <lombok.version>1.18.2</lombok.version>
     41   </properties>
     42 
     43   <dependencies>
     44     <!--1.spring相关-->
     45     <dependency>
     46       <groupId>org.springframework</groupId>
     47       <artifactId>spring-context</artifactId>
     48       <version>${spring.version}</version>
     49     </dependency>
     50     <dependency>
     51       <groupId>org.springframework</groupId>
     52       <artifactId>spring-orm</artifactId>
     53       <version>${spring.version}</version>
     54     </dependency>
     55     <dependency>
     56       <groupId>org.springframework</groupId>
     57       <artifactId>spring-tx</artifactId>
     58       <version>${spring.version}</version>
     59     </dependency>
     60     <dependency>
     61       <groupId>org.springframework</groupId>
     62       <artifactId>spring-aspects</artifactId>
     63       <version>${spring.version}</version>
     64     </dependency>
     65     <dependency>
     66       <groupId>org.springframework</groupId>
     67       <artifactId>spring-web</artifactId>
     68       <version>${spring.version}</version>
     69     </dependency>
     70     <dependency>
     71       <groupId>org.springframework</groupId>
     72       <artifactId>spring-test</artifactId>
     73       <version>${spring.version}</version>
     74     </dependency>
     75 
     76     <!--2.mybatis相关-->
     77     <dependency>
     78       <groupId>org.mybatis</groupId>
     79       <artifactId>mybatis</artifactId>
     80       <version>${mybatis.version}</version>
     81     </dependency>
     82     <!--mysql-->
     83     <dependency>
     84       <groupId>mysql</groupId>
     85       <artifactId>mysql-connector-java</artifactId>
     86       <version>${mysql.version}</version>
     87     </dependency>
     88     <!--pagehelper分页插件jar包依赖-->
     89     <dependency>
     90       <groupId>com.github.pagehelper</groupId>
     91       <artifactId>pagehelper</artifactId>
     92       <version>${pagehelper.version}</version>
     93     </dependency>
     94     <!--mybatis与spring集成jar包依赖-->
     95     <dependency>
     96       <groupId>org.mybatis</groupId>
     97       <artifactId>mybatis-spring</artifactId>
     98       <version>${mybatis.spring.version}</version>
     99     </dependency>
    100 
    101     <!--3.dbcp2连接池相关-->
    102     <dependency>
    103       <groupId>org.apache.commons</groupId>
    104       <artifactId>commons-dbcp2</artifactId>
    105       <version>${commons.dbcp2.version}</version>
    106     </dependency>
    107     <dependency>
    108       <groupId>org.apache.commons</groupId>
    109       <artifactId>commons-pool2</artifactId>
    110       <version>${commons.pool2.version}</version>
    111     </dependency>
    112 
    113     <!--4.log日志相关依赖-->
    114     <!--核心log4j2jar包-->
    115     <dependency>
    116       <groupId>org.apache.logging.log4j</groupId>
    117       <artifactId>log4j-core</artifactId>
    118       <version>${log4j2.version}</version>
    119     </dependency>
    120     <dependency>
    121       <groupId>org.apache.logging.log4j</groupId>
    122       <artifactId>log4j-api</artifactId>
    123       <version>${log4j2.version}</version>
    124     </dependency>
    125     <!--web工程需要包含log4j-web,非web工程不需要-->
    126     <dependency>
    127       <groupId>org.apache.logging.log4j</groupId>
    128       <artifactId>log4j-web</artifactId>
    129       <version>${log4j2.version}</version>
    130     </dependency>
    131 
    132     <!--5.其他-->
    133     <dependency>
    134       <groupId>junit</groupId>
    135       <artifactId>junit</artifactId>
    136       <version>${junit.version}</version>
    137       <scope>test</scope>
    138     </dependency>
    139     <dependency>
    140       <groupId>javax.servlet</groupId>
    141       <artifactId>javax.servlet-api</artifactId>
    142       <version>${servlet.version}</version>
    143       <scope>provided</scope>
    144     </dependency>
    145     <dependency>
    146       <groupId>org.projectlombok</groupId>
    147       <artifactId>lombok</artifactId>
    148       <version>${lombok.version}</version>
    149       <scope>provided</scope>
    150     </dependency>
    151 
    152   </dependencies>
    153 
    154   <build>
    155     <finalName>ssm</finalName>
    156     <resources>
    157       <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
    158       <resource>
    159         <directory>src/main/java</directory>
    160         <includes>
    161           <include>**/*.xml</include>
    162         </includes>
    163       </resource>
    164       <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
    165       <resource>
    166         <directory>src/main/resources</directory>
    167         <includes>
    168           <include>jdbc.properties</include>
    169           <include>*.xml</include>
    170         </includes>
    171       </resource>
    172     </resources>
    173     <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
    174       <plugins>
    175         <plugin>
    176           <groupId>org.apache.maven.plugins</groupId>
    177           <artifactId>maven-compiler-plugin</artifactId>
    178           <version>${maven.compiler.plugin.version}</version>
    179           <configuration>
    180             <source>${maven.compiler.source}</source>
    181             <target>${maven.compiler.target}</target>
    182             <encoding>${project.build.sourceEncoding}</encoding>
    183           </configuration>
    184         </plugin>
    185         <plugin>
    186           <groupId>org.mybatis.generator</groupId>
    187           <artifactId>mybatis-generator-maven-plugin</artifactId>
    188           <version>1.3.2</version>
    189           <dependencies>
    190             <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
    191             <dependency>
    192               <groupId>mysql</groupId>
    193               <artifactId>mysql-connector-java</artifactId>
    194               <version>${mysql.version}</version>
    195             </dependency>
    196           </dependencies>
    197           <configuration>
    198             <overwrite>true</overwrite>
    199           </configuration>
    200         </plugin>
    201       </plugins>
    202     </pluginManagement>
    203   </build>
    204 </project>

    利用mybatis逆向工程生成模型层层代码

    编写配置文件applicationContext-mybatis.xml

    注解式开发

    开启注解

       <!--1. 注解式开发 -->

       <!-- 注解驱动 -->

    1 <context:annotation-config/>

     <!-- 用注解方式注入bean,并指定查找范围:com.javaxl.ssm及子子孙孙包-->

    1  <context:component-scan base-package="com.javaxl.ssm"/>

    引入外部jdbc配置文件

    1 <context:property-placeholder location="classpath:jdbc.properties"/>

     配置dbcp2数据库连接池

    spring和mybatis整合

    注解式事物配置

    1 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    2         <property name="dataSource" ref="dataSource" />
    3 </bean>
    4  <tx:annotation-driven transaction-manager="transactionManager" />

     开启动态代理

    1 <aop:aspectj-autoproxy/>

    注解式开发

    @Repository:将DAO类声明为Bean

       @Service:通常作用在业务层

       @Constroller:通常作用在控制层,将在Spring MVC中使用

       @Component:是一个泛化的概念,仅仅表示spring中的一个组件(Bean),可以作用在任何层次

       @Scope:模式声明(singleton|prototype

       @Autowired:将自动在代码上下文与其匹配(默认是类型匹配)的Bean,并自动注入到相应的地方

       @Resource

       1@Resource后面没有任何内容,默认通过name属性去匹配bean,找不到再按type去匹配

       2)指定了name或者type则根据指定的类型去匹配bean

       3)指定了nametype则根据指定的nametype去匹配bean,任何一个不匹配都将报错

       问题:@Autowired@Resource两个注解的区别:

       1@Autowired默认按照byType方式进行bean匹配,@Resource默认按照byName方式进行bean匹配

       2@AutowiredSpring的注解,@ResourceJ2EE的注解,这个看一下导入注解的时候这两个注解的包名就一清二楚了

       Spring属于第三方的,J2EEJava自己的东西,因此,建议使用@Resource注解,以减少代码和Spring之间的耦合。

       @Transactional

       注:个人感觉注解式事务比以前的声明式事务更加麻烦,要写的东西更多

    applicationContext-mybatis.xml

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4        xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
     5        xmlns:aop="http://www.springframework.org/schema/aop"
     6        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">
     7     <!--1. 注解式开发 -->
     8     <!-- 注解驱动 -->
     9     <context:annotation-config/>
    10     <!-- 用注解方式注入bean,并指定查找范围:com.cgl.ssm及子子孙孙包-->
    11     <context:component-scan base-package="com.Mybatis.ssm"/>
    12 
    13     <context:property-placeholder location="classpath:jdbc.properties"/>
    14 
    15     <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
    16           destroy-method="close">
    17         <property name="driverClassName" value="${jdbc.driver}"/>
    18         <property name="url" value="${jdbc.url}"/>
    19         <property name="username" value="${jdbc.username}"/>
    20         <property name="password" value="${jdbc.password}"/>
    21         <!--初始连接数-->
    22         <property name="initialSize" value="10"/>
    23         <!--最大活动连接数-->
    24         <property name="maxTotal" value="100"/>
    25         <!--最大空闲连接数-->
    26         <property name="maxIdle" value="50"/>
    27         <!--最小空闲连接数-->
    28         <property name="minIdle" value="10"/>
    29         <!--设置为-1时,如果没有可用连接,连接池会一直无限期等待,直到获取到连接为止。-->
    30         <!--如果设置为N(毫秒),则连接池会等待N毫秒,等待不到,则抛出异常-->
    31         <property name="maxWaitMillis" value="-1"/>
    32     </bean>
    33 
    34     <!--4. spring和MyBatis整合 -->
    35     <!--1) 创建sqlSessionFactory-->
    36     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    37         <!-- 指定数据源 -->
    38         <property name="dataSource" ref="dataSource"/>
    39         <!-- 自动扫描XxxMapping.xml文件,**任意路径 -->
    40         <property name="mapperLocations" value="classpath*:com/Mybatis/ssm/**/mapper/*.xml"/>
    41         <!-- 指定别名 -->
    42         <property name="typeAliasesPackage" value="com/Mybatis/ssm/**/model"/>
    43         <!--配置pagehelper插件-->
    44         <property name="plugins">
    45             <array>
    46                 <bean class="com.github.pagehelper.PageInterceptor">
    47                     <property name="properties">
    48                         <value>
    49                             helperDialect=mysql
    50                         </value>
    51                     </property>
    52                 </bean>
    53             </array>
    54         </property>
    55     </bean>
    56 
    57     <!--2) 自动扫描com/cgl/ssm/**/mapper下的所有XxxMapper接口(其实就是DAO接口),并实现这些接口,-->
    58     <!--   即可直接在程序中使用dao接口,不用再获取sqlsession对象-->
    59     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    60         <!--basePackage 属性是映射器接口文件的包路径。-->
    61         <!--你可以使用分号或逗号 作为分隔符设置多于一个的包路径-->
    62         <property name="basePackage" value="com/Mybatis/ssm/**/mapper"/>
    63         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    64     </bean>
    65 
    66     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    67         <property name="dataSource" ref="dataSource" />
    68     </bean>
    69     <tx:annotation-driven transaction-manager="transactionManager" />
    70     <aop:aspectj-autoproxy/>
    71 </beans>

    applicationContext.xml

    1 ?xml version="1.0" encoding="UTF-8"?>
    2 <beans xmlns="http://www.springframework.org/schema/beans"
    3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    5     <!--整合mybatis框架-->
    6     <import resource="applicationContext-mybatis.xml"></import>
    7 </beans>

    BookService

     1 package com.Mybatis.ssm.service;
     2 
     3 import com.Mybatis.ssm.model.Book;
     4 import com.Mybatis.ssm.util.PageBean;
     5 
     6 import java.util.List;
     7 
     8 public interface BookService {
     9 
    10     int deleteByPrimaryKey(Integer bid);
    11 
    12     int insert(Book record);
    13 
    14     int insertSelective(Book record);
    15 
    16     Book selectByPrimaryKey(Integer bid);
    17 
    18     int updateByPrimaryKeySelective(Book record);
    19 
    20     int updateByPrimaryKey(Book record);
    21 
    22     List<Book> listPage(Book book, PageBean pageBean);
    23 }

    BookServiceImpl

     1 package com.Mybatis.ssm.service.impl;
     2 
     3 import com.Mybatis.ssm.mapper.BookMapper;
     4 import com.Mybatis.ssm.model.Book;
     5 import com.Mybatis.ssm.service.BookService;
     6 import com.Mybatis.ssm.util.PageBean;
     7 import org.springframework.beans.factory.annotation.Autowired;
     8 import org.springframework.stereotype.Service;
     9 
    10 import java.util.List;
    11 
    12 @Service
    13 public class BookServiceImpl implements BookService {
    14 
    15 //    @Resource   相当于spring 自动装配中的byName;  @Autowired 相当于byType
    16 
    17     @Autowired
    18     private BookMapper bookMapper;
    19     @Override
    20     public int deleteByPrimaryKey(Integer bid) {
    21         return bookMapper.deleteByPrimaryKey(bid);
    22     }
    23 
    24     @Override
    25     public int insert(Book record) {
    26         return bookMapper.insert(record);
    27     }
    28 
    29     @Override
    30     public int insertSelective(Book record) {
    31         return bookMapper.insertSelective(record);
    32     }
    33 
    34     @Override
    35     public Book selectByPrimaryKey(Integer bid) {
    36         return bookMapper.selectByPrimaryKey(bid);
    37     }
    38 
    39     @Override
    40     public int updateByPrimaryKeySelective(Book record) {
    41         return bookMapper.updateByPrimaryKeySelective(record);
    42     }
    43 
    44     @Override
    45     public int updateByPrimaryKey(Book record) {
    46         return bookMapper.updateByPrimaryKey(record);
    47     }
    48 
    49     @Override
    50     public List<Book> listPage(Book book, PageBean pageBean) {
    51 
    52         return bookMapper.listPage(book);
    53     }
    54 }

    SpringBaseTest

     1 package com.Mybatis.ssm;
     2 
     3 import org.junit.runner.RunWith;
     4 import org.springframework.test.context.ContextConfiguration;
     5 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
     6 
     7 @RunWith(SpringJUnit4ClassRunner.class)
     8 @ContextConfiguration(locations={"classpath:applicationContext.xml"})
     9 public class SpringJunitBaseTest {
    10 
    11 
    12 }

    BookServiceImplTest

    测试

     1 package com.Mybatis.ssm.service.impl;
     2 
     3 import com.Mybatis.ssm.SpringJunitBaseTest;
     4 import com.Mybatis.ssm.model.Book;
     5 import com.Mybatis.ssm.service.BookService;
     6 import com.Mybatis.ssm.util.PageBean;
     7 import com.Mybatis.ssm.util.StringUtils;
     8 import org.junit.After;
     9 import org.junit.Before;
    10 import org.junit.Test;
    11 import org.springframework.beans.factory.annotation.Autowired;
    12 
    13 import java.util.List;
    14 
    15 import static org.junit.Assert.*;
    16 
    17 public class BookServiceImplTest extends SpringJunitBaseTest {
    18 
    19     @Autowired
    20     private BookService bookService;
    21     @Before
    22     public void setUp() throws Exception {
    23     }
    24 
    25     @After
    26     public void tearDown() throws Exception {
    27     }
    28 
    29     @Test
    30     public void deleteByPrimaryKey() {
    31         bookService.deleteByPrimaryKey(1);
    32     }
    33 
    34     @Test
    35     public void selectByPrimaryKey() {
    36         System.out.println(this.bookService.selectByPrimaryKey(12));
    37     }
    38 
    39 }

    分页优化,使用AOP编程解决分页代码重复的问题

    PagerAspect

     1 package com.Mybatis.ssm.component;
     2 
     3 import com.Mybatis.ssm.util.PageBean;
     4 import com.github.pagehelper.PageHelper;
     5 import com.github.pagehelper.PageInfo;
     6 import org.aspectj.lang.ProceedingJoinPoint;
     7 import org.aspectj.lang.annotation.Around;
     8 import org.aspectj.lang.annotation.Aspect;
     9 import sun.misc.Contended;
    10 
    11 import java.util.List;
    12 
    13 @Contended
    14 @Aspect
    15 public class PagerAspect {
    16 
    17     @Around("execution(* *..*Service.*Pager(..))")
    18     public Object invoke(ProceedingJoinPoint args) throws Throwable{
    19 //        符合* *..*Service.*Pager(..)规则的方法,调用时所携带的参数
    20         Object[] args1 = args.getArgs();
    21         PageBean pageBean = null;
    22         for (Object o : args1) {
    23             if (o instanceof PageBean) {
    24                 pageBean = (PageBean) o;
    25                 break;
    26             }
    27         }
    28         if(pageBean != null && pageBean.isPagination()){
    29             PageHelper.startPage(pageBean.getMaxPage(),pageBean.getRows());
    30         }
    31         Object list = args.proceed(args1);
    32         if(pageBean != null && pageBean.isPagination()){
    33             PageInfo pageInfo = new PageInfo((List)list);
    34             pageBean.setTotal(pageInfo.getTotal()+"");
    35         }
    36         return list;
    37     }
    38 }

    JUnit测试

    BookServiceImplTest

     1 package com.Mybatis.ssm.service.impl;
     2 
     3 import com.Mybatis.ssm.SpringJunitBaseTest;
     4 import com.Mybatis.ssm.model.Book;
     5 import com.Mybatis.ssm.service.BookService;
     6 import com.Mybatis.ssm.util.PageBean;
     7 import com.Mybatis.ssm.util.StringUtils;
     8 import org.junit.After;
     9 import org.junit.Before;
    10 import org.junit.Test;
    11 import org.springframework.beans.factory.annotation.Autowired;
    12 
    13 import java.util.List;
    14 
    15 import static org.junit.Assert.*;
    16 
    17 public class BookServiceImplTest extends SpringJunitBaseTest {
    18 
    19     @Autowired
    20     private BookService bookService;
    21     @Before
    22     public void setUp() throws Exception {
    23     }
    24 
    25     @After
    26     public void tearDown() throws Exception {
    27     }
    28 
    29     @Test
    30     public void listPage() {
    31         Book book = new Book();
    32         book.setBname(StringUtils.toLikeStr("圣墟"));
    33         PageBean pageBean = new PageBean();
    34         pageBean.setPagination(false);
    35         List<Book> books = this.bookService.listPage(book, pageBean);
    36         for (Book b : books){
    37             System.out.println(b);
    38         }
    39 
    40     }
    41 }
  • 相关阅读:
    jquery
    为什么用bower 安装bootstrap而不用npm来安装?
    Grunt 入门操作指南
    微信页面识别二维码非常不灵敏 而且识别的位置偏移 的解决方案
    osx安装sass
    sass安装和语法
    ES6新特性概述
    link-hover-visited-active
    css HACK
    CSS3文本溢出显示省略号
  • 原文地址:https://www.cnblogs.com/xcn123/p/11708358.html
Copyright © 2020-2023  润新知