spring-boot集成mybatis-plus

北慕城南 提交于 2020-08-11 08:26:00

1) 引入相关jar包

<!-- 引入mybatis-plus包 -->
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>${mybatis-plus.version}</version>
</dependency>
<!-- 引入mysql驱动包 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>

2) 编写配置文件

spring:
  datasource:
#    driver-class-name:
    url: jdbc:mysql://127.0.0.1:3306/DEMO_DB?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&serverTimezone=GMT%2B8
    username: root
    password: '123456'

3) 配置包扫描路径(必须,要不然启动报错)

@SpringBootApplication
@EnableWebMvc
@ComponentScan("com.zhoulp.demo")
// 一个*代表任意字符串,但只代表一级包,比如可以扫到com.zhoulp.aaa.mapper,不能扫到com.zhoulp.aaa.bbb.mapper
// 两个*代表任意个包,比如可以扫到com.zhoulp.aaa.mapper,也可以扫到com.zhoulp.aaa.bbb.mapper
@MapperScan({"com.zhoulp.demo.**.dao"})
public class DemoWebApplication {
	public static void main(String[] args) {
		SpringApplication.run(DemoWebApplication.class, args);
	}
}

4) 实现表映射类,必须有@TableName,@TableId注解

@ApiModel
@TableName("t_user")
public class UserEntity {

	@ApiModelProperty(value = "用户ID")
	@TableId("id")
	private String id;
	
	@ApiModelProperty(value = "手机号")
	@TableField("mobile")
	private String mobile;
	
}

5) 编写Mapper接口,继承BaseMapper

@Repository
public interface UserMapper extends BaseMapper<UserEntity> {

}

6) 编写Service层,接口继承IService接口,实现类继承ServiceImpl

public interface UserService extends IService<UserEntity> {

}
@Named("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

}

7) 添加分页插件(分页必须)

@Configuration
@EnableAsync
public class MyBatisPlusConfig {
	/**
	* <p>分页插件</p>
	*/
	@Bean
	public PaginationInterceptor paginationInterceptor() {
		PaginationInterceptor interceptor = new PaginationInterceptor();
		// 分页查询默认一页大小上限500条,-1不限制
		interceptor.setLimit(-1);
		interceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
		return interceptor;
	}
}

8) 配置打印sql执行语句

有两种方式:

1、启用mybatis-plus日志配置方式,但是这种方式也会同时打印结果集

mybatis-plus:
  configuration:
#    打印sql语句,也打印结果集
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

2、启用日志包级别方式

logging:
  level:
#    打印sql语句(DEBUG),打印结果集(TRACE)
    com.zhoulp.user.dao: debug
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!