如果项目中使用到了MyBatis框架,那么使用通用Mapper和PageHelper分页插件将极大的简化我们的操作。通用Mapper可以简化对单表的CRUD操作,PageHelper分页插件可以帮我们自动拼接分页SQL,并且可以使用MyBatis Geneator来自动生成实体类,Mapper接口和Mapper xml代码,非常的方便。插件地址及作者链接https://gitee.com/free 。
引入依赖
这里使用Spring Boot来构建,可参考Spring-Boot中使用Mybatis.html搭建一个Spring boot + MyBatis的框架,然后在pom中引入:
<!-- mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <!-- 通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>1.1.5</version><strong>本文来源gaodai#ma#com搞@@代~&码*网2</strong> </dependency> <!-- pagehelper 分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.3</version> </dependency>
接着在pom中配置MyBatis Geneator:
<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <dependencies> <dependency> <!-- 数据库连接驱动 --> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>6.0</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>3.4.0</version> </dependency> </dependencies> <executions> <execution> <id>Generate MyBatis Artifacts</id> <phase>package</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <!--允许移动生成的文件 --> <verbose>true</verbose> <!-- 是否覆盖 --> <overwrite>true</overwrite> <!-- 自动生成的配置 --> <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile> </configuration> </plugin> </plugins> </build>
src/main/resources/mybatis-generator.xml为生成器的配置,下文会介绍到。
配置插件
在Spring Boot配置文件application.yml中配置MyBatis:
mybatis: # type-aliases扫描路径 type-aliases-package: com.springboot.bean # mapper xml实现扫描路径 mapper-locations: classpath:mapper/*.xml property: order: BEFORE
接下来开始配置插件。
配置通用Mapper
在Spring Boot配置文件application.yml中配置通用Mapper:
#mappers 多个接口时逗号隔开 mapper: mappers: com.springboot.config.MyMapper not-empty: false identity: oracle
关于参数的说明,参考https://gitee.com/free/Mapper/blob/master/wiki/mapper3/2.Integration.md中的可配参数介绍。