前言
听说你又有新需求了?
什么?又是对某些表的增删改查?
什么?还要从数据库一直写到dao层?还要配置mapper.xml文件?完事儿之后还要写service层、controller层?
什么?遇到条件查询还要写dao层和xml文件中的sql语句?
什么?有新需求了,要加分页?使用pageHelper文件?
搬砖的活儿怎么配得上你一代码神的气质?
少年,看你筋骨奇特,配上mybatis plus必能摆脱搬砖的苦恼。一扫以上所有问题!
废话不多说,项目git地址 https://github.com/KouLouYiMaSi/mybatis-plus.git
Mybatis Plus优势
- 可以提供代码层面的条件查询
- 可以快速生成代码
- 集成了分页插件
SpringBoot整合实战
step1
配置maven依赖,最重要的是上面的第一个和第二个,第二个负责生成代码做模板
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.16</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
step2
配置application.xml文件,有了这个配置就不用写druid的配置类了,这是新版Druid的糖
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
username: username
password: password
druid:
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
# 配置DruidStatFilter
web-stat-filter:
enabled: true
url-pattern: "/*"
exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
# 配置DruidStatViewServlet
stat-view-servlet:
url-pattern: "/druid/*"
# IP白名单(没有配置或者为空,则允许所有访问)
allow: 127.0.0.1,192.168.163.1
# IP黑名单 (存在共同时,deny优先于allow)
deny: 192.168.1.73
# 禁用HTML页面上的“Reset All”功能
reset-enable: false
# 登录名
login-username: admin
# 登录密码
login-password: 123456
mybatis-plus:
mapper-locations: classpath:/com/example/demo/mapper/*/*.xml
typeAliasesPackage: com.example.demo.entity
global-config:
id-type: 2
field-strategy: 2
db-column-underline: true
refresh-mapper: true
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
server:
port: 8082
step3
配置生成代码的类和分页插件配置类
package com.example.demo.config;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
/**
* 小混蛋
*/
public class CodeGenerator {
public static final String DB_URL = "jdbc:mysql://localhost:3306/hawkeye?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true";
public static final String USER_NAME = "用户名";
public static final String PASSWORD = "密码";
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String AUTHOR = "作者名称";
//生成的文件输出到哪个目录
public static final String OUTPUT_FILE = "D:\\codeGen";
//包名,会按照com/example/demo这种形式生成类
public static final String PACKAGE = "com.example.demo";
//TODO 更多配置请参考http://mp.baomidou.com/#/generate-code
public void generateByTables(boolean serviceNameStartWithI, String... tableNames) {
GlobalConfig config = new GlobalConfig();
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL)
.setUrl(DB_URL)
.setUsername(USER_NAME)
.setPassword(PASSWORD)
.setDriverName(DRIVER);
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig
.setCapitalMode(true)
.setEntityLombokModel(false)
.setDbColumnUnderline(true)
.setNaming(NamingStrategy.underline_to_camel)
.setInclude(tableNames);//修改替换成你需要的表名,多个表名传数组
config.setActiveRecord(false)
.setAuthor(AUTHOR)
.setOutputDir(OUTPUT_FILE)
.setFileOverride(true);
if (!serviceNameStartWithI) {
config.setServiceName("%sService");
}
new AutoGenerator().setGlobalConfig(config)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(
new PackageConfig()
.setParent(PACKAGE)
.setController("controller")
.setEntity("entity")
).execute();
}
}
package com.example.demo.config;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.example.demo.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
step4
写一个junit test类,用于生成代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Test
public void contextLoads() {
CodeGenerator gse = new CodeGenerator();
//要给那些表生成
gse.generateByTables(false,"tb_user", "tb_role","tb_permission","tb_user_role","tb_role_permission");
}
}
step5
执行junit test类,生成代码之后就可以用了
mybatis-plus用法
- mapper层和service层基本上啥也不用动,当然,如果你需要其他逻辑可以在service层添加方法
- controller直接注入service直接调用就ok 了
- 条件查询用EntityWrapper,输入点之后ide会给你你想要的提示
- 分页查询只需要selectPage方法即可,就是这么简单
@Controller
@RequestMapping("/tbUser")
public class TbUserController {
@Autowired
private TbUserService tbUserService;
@RequestMapping("/all")
@ResponseBody
public List<TbUser> getAll(){
return tbUserService.selectList(new EntityWrapper<TbUser>());
}
@RequestMapping("/allbypage")
@ResponseBody
public Page<TbUser> getAllByPage(Integer pageNum,Integer pageSize){
return tbUserService.selectPage(new Page<TbUser>(pageNum,pageSize));
}
@RequestMapping("/insert")
@ResponseBody
public boolean insert(TbUser tbUser){
return tbUserService.insert(tbUser);
}
@RequestMapping("/insert")
@ResponseBody
public boolean delete(Integer id){
return tbUserService.deleteById(id);
}
@RequestMapping("/insert")
@ResponseBody
public List<TbUser> getUserById(Integer uid){
return tbUserService.selectList(
new EntityWrapper<TbUser>()
.eq("uid",uid)
);
}
}
总结
以后再做管理系统建完表就直接生成,反正一般都是给内部人用,后期涉及到优化也就是加索引什么的。
网友评论