«

Spring怎么集成MyBatis及Aop分页

时间:2024-7-14 15:41     作者:韩俊     分类: Java


这篇“Spring怎么集成MyBatis及Aop分页”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Spring怎么集成MyBatis及Aop分页”文章吧。

一、首先我们先创建一个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
esmysqlmysql-connector-java8.0.30mysql-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/spring/**/mapper/*.xml"/>
        <!--配置需要定义别名的实体类的包-->
        <property name="typeAliasesPackage" value="com.zking.spring.model"/>
        <!--配置需要mybatis的主配置文件-->
        <property name="configLocation" value="Mybatis.xml"/>
        <!--        配置pagehelper插件-->
        <!--        注意其他配置-->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!--使用下面的方式配置参数,一行配置一个 -->
                        <value>
                            helperDialect=mysql
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>
    <!-- 配置mapper接口的扫描器,将Mapper接口的实现类自动注入到IoC容器中
     实现类Bean的名称默认为接口类名的首字母小写 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- basePackage属性指定自动扫描mapper接口所在的包 -->
        <property name="basePackage" value="com/zking/ssm/spring/**/mapper"/>
    </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 = 

标签: java spring

热门推荐