Spring集成MyBatis 及Aop分页的实现代码

2023-05-14 08:05:55 代码 分页 集成

一、首先我们先创建一个Maven项目

把我们需要的包先准备好

 1.打开pom.xml文件引入依赖,以下是整个pom.xml文件

<project xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zking</groupId>
    <artifactId>untitled12</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>untitled12 Maven WEBapp</name>
    <url>http://maven.apache.org</url>
    <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>
 
        <!--junit+servlet-->
        <junit.version>4.12</junit.version>
        <servlet.version>4.0.1</servlet.version>
        <!--spring-->
        <spring.version>5.3.18</spring.version>
        <!--mybatis-->
        <mybatis.version>3.4.5</mybatis.version>
        <!--Mysql-->
        <mysql.version>8.0.30</mysql.version>
        <!--pagehelper-->
        <pagehelper.version>5.1.2</pagehelper.version>
        <!--mybatis-spring-->
        <mybatis.spring.version>1.3.1</mybatis.spring.version>
        <!--dbcp2-->
        <commons.dbcp2.version>2.1.1</commons.dbcp2.version>
        <commons.pool2.version>2.4.3</commons.pool2.version>
        <!--log4j2-->
        <log4j2.version>2.9.1</log4j2.version>
        <slf4j.version>1.7.7</slf4j.version>
        <log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
        <!--lombok-->
        <lombok.version>1.18.12</lombok.version>
    </properties>
    <dependencies>
        <!--junit+servlet-->
        <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>
        </dependency>
 
        <!--spring-->
        <!-- ********************** spring依赖 ********************** -->
        <!--1)spring核心依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring ioc依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring 扩展依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--2)spring dao层依赖-->
        <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>
        <!--3)aop相关依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--4)spring web相关依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--5) spring test相关依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
 
            <groupId>org.mybatis.generator</groupId>
 
            <artifactId>mybatis-generator-core</artifactId>
 
            <version>1.3.5</version>
        </dependency>
 
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
 
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
 
        <!--pagehelper-->
        <dependency>
            <groupId>com.GitHub.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>${pagehelper.version}</version>
        </dependency>
 
        <!--mybatis与spring集成依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>
        <!-- druid阿里的数据库连接池 -->
        <dependency>
            <artifactId>druid</artifactId>
            <groupId>com.alibaba</groupId>
            <version>1.1.10</version>
        </dependency>
        <!--dbcp2连接池-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>${commons.dbcp2.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-pool2</artifactId>
                    <groupId>org.apache.commons</groupId>
                </exclusion>
            </exclusions>
        </dependency>
 
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>${commons.pool2.version}</version>
        </dependency>
 
        <!--日志 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- slf4j日志包 -->
        <dependency>
            <artifactId>slf4j-log4j12</artifactId>
            <groupId>org.slf4j</groupId>
            <version>1.7.25</version>
        </dependency>
 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>untitled12</finalName>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2.引入依赖之后咱们导入需要的xml文件

 1.generatorConfig.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
    <!-- 引入配置文件 -->
    <properties resource="jdbc.properties"/>
 
    <!--指定数据库jdbc驱动jar包的位置-->
    <classPathEntry location="D:\config\res\mysql\mysql-connector-java\8.0.30\mysql-connector-java-8.0.30.jar"/>
 
    <!-- 一个数据库一个context -->
    <context id="infoGuardian">
        <!-- 注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
            <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
        </commentGenerator>
 
        <!-- jdbc连接 -->
        <jdbcConnection driverClass="${jdbc.driver}"
                        connectionURL="${jdbc.url}" userId="${jdbc.username}" passWord="${jdbc.password}"/>
 
        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
 
        <!-- 01 指定javaBean生成的位置 -->
        <!-- targetPackage:指定生成的model生成所在的包名 -->
        <!-- targetProject:指定在该项目下所在的路径  -->
        <javaModelGenerator targetPackage="com.zking.SSM.spring.model"
                            targetProject="src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
            <property name="trimStrings" value="false"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>
 
        <!-- 02 指定sql映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.zking.ssm.spring.mapper"
                         targetProject="src/main/resources">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
 
        <!-- 03 生成XxxMapper接口 -->
        <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
        <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
        <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
        <javaClientGenerator targetPackage="com.zking.ssm.spring.mapper"
                             targetProject="src/main/java" type="XMLMAPPER">
            <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
 
        <!-- 配置表信息 -->
        <!-- schema即为数据库名 -->
        <!-- tableName为对应的数据库表 -->
        <!-- domainObjectName是要生成的实体类 -->
        <!-- enable*ByExample是否生成 example类 -->
        <table schema="" tableName="t_student" domainObjectName="Student"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
            <!--            &lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;-->
            <!--            &lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;-->
            <!--            &lt;!&ndash; 指定列的java数据类型 &ndash;&gt;-->
            <!--            &lt;!&ndash; <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;-->
        </table>
    </context>
</generatorConfiguration>

这是生成那些我们的实体类和mapper层还有对应mapper层的配置文件

2.jdbc.properties配置文件

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/y1?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=root123

3.log4j.properties配置文件

log4j.rootLogger=DEBUG, stdout 
log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

把以上配置好就可以进行生成那些代码了

然后打开Maven这个控制器

然后点击mybatis-generator运行他就行了,然后就会自动给你生成这些代码了

二、开始Spring集成MyBatis

 1、首先我们先创建一个MyBatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 控制台查看拼接好的sql, settings标签要放在前面,顺序错了这个配置文件会报错-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
 
    <!-- 批量定义别名,包下面的类批量取别名,别名就是类名(首字母小写) -->
    <typeAliases>
        <package name="com.zking.ssm"/>
    </typeAliases>
</configuration>

2、之后就是创建Spring文件这个文件是Spring帮我们管理MyBatis

可能有些东西不同但是这个文件是必备的

<?xml version="1.0" encoding="UTF-8"?>
<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" xmlns="http://www.springframework.org/schema/beans"
       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 https://www.springframework.org/schema/aop/spring-aop.xsd">
 
    <!--<context:component-scan base-package="com.tjise.bean"/>-->
    <context:component-scan base-package="com.zking.ssm"/>
    <!-- 加载数据库连接信息的属性文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- 开启事务管理 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource"/>
    </bean>
    <!-- 配置Druid数据源的Bean -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
 
    <!-- 配置SessionFactory的Bean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置mapper的路径-->
        <property name="mapperLocations" value="classpath:com/zking/ssm/springmappermapper"/>
    </bean>
    <!--    <tx:advice id="TxAdvice" transaction-manager="transactionManager">-->
    <!--        <tx:attributes>-->
    <!--            <tx:method name="Insert*" isolation="REPEATABLE_READ" propagation="REQUIRED"/>-->
    <!--            <tx:method name="Update*" isolation="REPEATABLE_READ" propagation="REQUIRED"/>-->
    <!--            <tx:method name="Delete*" isolation="REPEATABLE_READ" propagation="REQUIRED"/>-->
    <!--            <tx:method name="Query*" isolation="REPEATABLE_READ" propagation="SUPPORTS"/>-->
    <!--        </tx:attributes>-->
    <!--    </tx:advice>-->
    <!--5.开启注解式事务-->
    <!--    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">-->
    <!--        <property name="dataSource" ref="dataSource"/>-->
    <!--    </bean>-->
    <!--6.开启动态代理-->
    <aop:aspectj-autoproxy/>
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

接下来就是我们写service来测试这个集成好没有,切记记得改jdbc.properties文件里面的参数和驱动程序要和你本机相同

1.创建IStudent借口

public interface IStudent {
    List<Student> listPager(Student student, PageBean pageBean);
 
    List<Student> selectByPager(@Param("student") Student student, PageBean pageBean);
}

2.实现这个借口

@Service
public class StudentImpl implements IStudent {
//依赖注入,不写这个会报空值异常
    @Autowired
    private StudentMapper studentMapper;
 
    @Override
    public List<Student> listPager(Student student, PageBean pageBean) {
        return studentMapper.listPager(student, pageBean);
    }
 
    @Paging //这是一个分页的注解
    @Override
    public List<Student> selectByPager(Student student, PageBean pageBean) {
        return studentMapper.list(student, pageBean);
    }
}

然后就可以去test 目录底下编写测试类了 

 测试类的编写

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:Spring.xml")
public class IStudentTest{
    @Autowired
    private IStudent iStudent;
 
   @Test
    public void Pager() {
        Student student = new Student();
        student.setSname("");
        List<Student> students = iStudent.selectByPager(student, new PageBean());
        students.forEach(t -> System.out.println(t));
    }
}

然后就是去编写咱们的aop切面编程

首先我们要一个分页对象

 PageBean.java

package com.zking.ssm.spring.util;
 
import lombok.*;
import lombok.experimental.Accessors;
 
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
 
//val : 最终局部变量
//@NonNull : 让你不在担忧并且爱上NullPointerException(可以在参数的类型前面加上注解)
//@CleanUp : 自动资源管理:不用再在finally中添加资源的close方法
//@Setter/@Getter : 自动生成set和get方法
//@ToString : 自动生成toString方法
//@EqualsAndHashcode : 从对象的字段中生成hashCode和equals的实现
//@NoArgsConstructor/@RequiredArgsConstructor/@AllArgsConstructor
//自动生成构造方法
//@Data : 自动生成set/get方法,toString方法,equals方法,hashCode方法,不带参数的构造方法
//@Value : 用于注解final类
//@Builder : 产生复杂的构建器api类
//@SneakyThrows : 异常处理(谨慎使用)
//@Synchronized : 同步方法安全的转化
//@Getter(lazy=true) :
//@Log : 支持各种logger对象,使用时用对应的注解,如:@Log4j
@AllArgsConstructor
@NoArgsConstructor
@ToString
@EqualsAndHashCode
@Accessors(chain = true)
@Data

public class PageBean {
 
    private Integer total;  //数据库的总条数
    private Integer page = 1; //当前页数
    private Integer row = 5; //当前显示的条数
    private boolean pagination = true; //是否需要分页
    private String url;
    private Map<String, String[]> ms;
 
    public PageBean(HttpServletRequest req) {
        String page = req.getParameter("page");
        String row = req.getParameter("row");
        if (page != null && page.length() > 0) {
            this.setPage(Integer.parseInt(page));
        }
        if (row != null && row.length() > 0) {
            this.setRow(Integer.parseInt(row));
        }
        String pagination = req.getParameter("pagination");
        if (pagination != null && pagination.equals("false")) {
            this.setPagination(false);
        }
        this.ms = req.getParameterMap();
    }
 
    
    public Integer start() {
        return (page - 1) * row;
    }
 
    
    public Integer max() {
        return total % row == 0 ? total / row : total / row + 1;
    }
 
    
    public Integer next() {
        return Math.min(page + 1, max());
    }
 
    
    public Integer prev() {
        return Math.max(page - 1, 1);
    }
}

然后我们要编写aop切面编程了

PageAspect.java

package com.zking.ssm.spring.aop;
 
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zking.ssm.spring.util.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 {
    @Around("execution(* *..*Service.*Pager(..))")
    public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取目标方法的执行参数
        Object[] args = joinPoint.getArgs();
        //定义PageBean对象
        PageBean pageBean = null;
        for (Object param : args) {
            //判断执行参数中是否有PageBean对象
            if (param instanceof PageBean) {
                pageBean = (PageBean) param;
                break;
            }
        }
        //判断是否分页
        if (pageBean != null && pageBean.isPagination()) {
            PageHelper.startPage(pageBean.getPage(), pageBean.getRow());
        }
        Object returnValue = joinPoint.proceed(args);
 
        if (pageBean != null && pageBean.isPagination()) {
            if (null != returnValue && returnValue instanceof List) {
                List list = (List) returnValue;
                PageInfo pageInfo = new PageInfo(list);
                pageBean.setTotal((int) pageInfo.getTotal());
            }
        }
        return returnValue;
    }
}

@Around("execution(* *..*Service.*Pager(..))")的意思是环绕通知然后里面的是必须是打了@Service注解的类才能识别到,*Pager就是以Pager结尾的前面所以的名字都可以识别到,然后(..)是方法参数不限制

编写好之后

就可以去测试了

但是这样会有识别不到的风险

所以咱们使用注解进行分页

package com.zking.ssm.spring.aop;
 
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zking.ssm.spring.util.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 PagerAop {
    //环绕通知  自定义注解 分辨是否调用
    @Around("@annotation(com.zking.ssm.spring.interfaces.Paging)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取目标方法的所有参数
        Object[] args = joinPoint.getArgs();
        PageBean pag = null;
        for (Object arg : args) {
            if (arg instanceof PageBean) {
                pag = (PageBean) arg;
                if (pag != null && pag.isPagination()) {
                    PageHelper.startPage(pag.getPage(), pag.getRow());
                }
            }
        }
        Object proceed = joinPoint.proceed();
        if (pag != null && pag.isPagination()) {
            PageInfo info = new PageInfo((List) proceed);
            pag.setTotal((int) info.getTotal());
        }
        return proceed;
    }
}

然后就是写@Paging 

//编译加载
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.PARAMETER})
public @interface Paging {
 
}

然后就可以在你要实现的类中打上注解就行了

到此这篇关于Spring集成MyBatis 及Aop分页的实现的文章就介绍到这了,更多相关Spring集成MyBatis内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章