您的位置:首页 > 其它

Mybatis-plus简单使用

2020-07-16 05:04 183 查看

目录

Mybatis-Plus结合Springboot简单使用

Maven依赖

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!--  代码生成器依赖  -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

<build>
<!--  解决mapper.xml编译是不在target中  -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

Springboot配置

server:
port: 8888

spring:
application:
name: service-mybatisplus #不要用下划线
profiles:
active: dev
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis-plus?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8

#mybatisplus日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:com/scofield/mybatisplus/mapper/xml/*.xml #mapper所在包路径

Mybaits-Plus配置类

@Configuration
@MapperScan("com.scofield.mybatisplus.mapper") //扫描mapper包
public class MybatisPlusConfig {

//逻辑删除插件
@Bean
public ISqlInjector iSqlInjector() {
return new LogicSqlInjector();
}

//分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
}

Mybaits-Plus的Handler类

@Component
public class UserMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
//自动填充时间
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}

@Override
public void updateFill(MetaObject metaObject) {
//自动更新时间
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}

代码生成器

public class CodeGenerator {
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();

// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir("D:\\ideaproject\\mybaitsplus-demo" + "/src/main/java");//代码输出到哪里

gc.setAuthor("scofield"); //作者
gc.setOpen(false);//生成后是否打开资源管理器
gc.setSwagger2(true);//实体属性 Swagger2 注解
gc.setServiceName("%sService");//去掉service接口的首字母I
gc.setIdType(IdType.ID_WORKER_STR);//主键策略,如果是char就是ID_WORKER_STR,int就是ID_WORKER
gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
mpg.setGlobalConfig(gc);

// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis-plus?serverTimezone=GMT%2B8&useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);//设置数据库类型
mpg.setDataSource(dsc);

// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.scofield");
pc.setModuleName("mybatisplus");//包名
pc.setController("controller");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);

// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("user");//表名称

strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);//lombok模型
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.execute();
}
}

需要修改的是:

gc.setOutputDir("D:\\ideaproject\\mybaitsplus-demo" + "/src/main/java");
代码最终生成路径。
pc.setModuleName("mybatisplus");
包名。
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis-plus?serverTimezone=GMT%2B8&useUnicode=true&useSSL=false&characterEncoding=utf8");
数据库名。
strategy.setInclude("user");
表名称。

更多细节可到官方查看:https://mp.baomidou.com/

创建数据库和创建mybatis-plus表

CREATE TABLE `user` (
`id` CHAR(19) NOT NULL COMMENT '用户ID',
`name` VARCHAR(20) NOT NULL COMMENT '用户姓名',
`intro` VARCHAR(500) NOT NULL DEFAULT '' COMMENT '用户简介',
`avatar` VARCHAR(255) DEFAULT NULL COMMENT '用户头像',
`sort` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '排序',
`is_deleted` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0' COMMENT '逻辑删除 1(true)已删除, 0(false)未删除',
`gmt_create` DATETIME NOT NULL COMMENT '创建时间',
`gmt_modified` DATETIME NOT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT='用户';

执行代码生成器,生成代码

自动生成时间

实体类中加注解

@ApiModelProperty(value = "逻辑删除 1(true)已删除, 0(false)未删除")
@TableLogic
private Boolean isDeleted;

@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;

@ApiModelProperty(value = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;

测试

  1. 简单Controller测试
@RestController
@RequestMapping("/mybatisplus/user")
public class UserController {

@Autowired
private UserService userService;

@GetMapping("insert")
public List<User> insert(){
User user = new User();
user.setName("二狗");
user.setIntro("职业法师");
userService.save(user);
return userService.list(null);
}
}
  1. swagger配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Bean
public Docket docket1(Environment environment)
{
Profiles profiles = Profiles.of("test","dev");
boolean flag = environment.acceptsProfiles(profiles);

return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(flag)
.groupName("开发")
.select()
//记得修改包名
.apis(RequestHandlerSelectors.basePackage("com.scofield"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger接口列表")
.description("接口")
.termsOfServiceUrl("http://localhost:8081/swagger-ui.html")
.contact(new Contact("hello", "http://www.baidu.com", "9999999@qq.com"))
.version("1.1.0")
.build();
}
}
  1. 启动
@SpringBootApplication
@ComponentScan("com.scofield.mybatisplus")
public class MPApplication {
public static void main(String[] args) {
SpringApplication.run(MPApplication.class,args);
}
}
  1. 访问
    http://localhost:8888/swagger-ui.html

项目模板可到码云下载:https://gitee.com/ScofieldLee/mybatisplus-demo.git

大吉大利,今晚吃鸡!!!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: