springboot 使用mybatis 通用Mapper,pagehelper

时间:2023-03-09 21:30:00
springboot 使用mybatis 通用Mapper,pagehelper

首先需要maven导入需要的包,这里用的是sqlserver,druid,jtds连接数据库

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.27</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
<!--mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
<!--pagehelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>

然后在application.properties中配置使用

# 驱动配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:jtds:sqlserver://路径/库
spring.datasource.username = **
spring.datasource.password = **
spring.datasource.driverClassName = net.sourceforge.jtds.jdbc.Driver #mybatis
mybatis.typeAliasesPackage=com.example.bean
mybatis.mapperLocations=classpath*:/mybatis/mapper/*Mapper.xml
mybatis.configuration.use-generated-keys=true
mybatis.configuration.mapUnderscoreToCamelCase=true #分页插件
pagehelper.helperDialect=sqlserver
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

其中:

com.example.bean:放置数据库实体类

mybatis/mapper:mybatis的mapper.xml(自定义方法配置)

springboot 使用mybatis 通用Mapper,pagehelper

接口类自定义基类IBaseMapper(注意:不要跟其他mapper类放在一起)

/**
 * 通用 Mapper接口
*
* @author sky
* @version 1.0
*/ public interface IBaseMapper<T extends AbstractDBEntity> extends Mapper<T>, MySqlMapper<T> { }

在入口类加上(其中com.example.mapper为mapper类放置包名)

@MapperScan(basePackages = { "com.example.mapper" })

这样就可以使用mybatis了

配置通用mapper

网上的方法在配置中使用mapper.mappers等等不知道为什么不行,在这里使用@Configuration的方式,注意入口类添加@ComponentScan扫描

新建MapperConfig类

/**
* @author sky
* @version 1.0
*/
@Configuration
public class MapperConfig { @Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.example.mapper");
Properties propertiesMapper = new Properties();
//通用mapper位置,不要和其他mapper、dao放在同一个目录
propertiesMapper.setProperty("mappers", IBaseMapper.class.getName());
propertiesMapper.setProperty("notEmpty", "false");
mapperScannerConfigurer.setProperties(
propertiesMapper);
return mapperScannerConfigurer;
} }

测试新建mapper实现:()

/**
* @author sky
* @version 1.0
*/
public interface RegionMapper extends IBaseMapper<Region> {
}

这里就不做多实现了。。