快速入门
官网文档也有入门介绍,如果有耐心和一定基础的小伙伴可以直接看官网传送门
准备依赖
1.mybatis-plus依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
2.mysql驱动JDBC依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
3.mysql驱动、JDBC和其他springboot依赖可以在IDEA中构建springboot项目时选择添加,这里就不加概述。
准备数据
创建user表
DROP DATABASE IF EXISTS mybatis_plus;
CREATE DATABASE mybatis_plus;
USE mybatis_plus;
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
create_time DATETIME COMMENT '创建时间',
update_time DATETIME COMMENT '更新时间',
PRIMARY KEY (id)
);
DELETE FROM user where 1 = 1;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
初始化工程
用IDEA初始化一个springboot项目
配置数据源
在resource目录下的配置文件里配置自己的数据源,建议在application.yml中配置
spring:
datasource:
username: root
password: nihao123
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=true&useUnicode=true&characterEcoding=utf-8
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
注意,我这里使用的mysql驱动是8+,在url中还需要配置时区,因为我在mysql配置文件中设置了默认时区,所以这里我没有配置时区。如果没有设置时区请加上serverTimezone=Asia/Shanghai.
另外,如果mysql驱动用的5+版本则应这样driver-class-name: com.mysql.jdbc.Driver配置驱动。
下面的mybatis-plus配置是开启日志,因为我没有导入其他的日志依赖,所以用的是自带的日志
创建User实体类
在pojo包下创建User对象,这里我引入了Lombok,用Lombok给对象创建构造器以及getter和setter
注意:若之前在IDEA中并未使用过Lombok,请先在IDEA中安装Lombok插件,Lombok
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.Date;
@ToString
@AllArgsConstructor
@Data
@NoArgsConstructor
public class User {
@TableId(type = IdType.AUTO)
private long id;
private String name;
private int age;
private String email;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
这里的@TableField后面会讲到,可以先暂时跳过
配置Mybatis-Plus
在main/src目录下创建mapper文件夹,在mapper文件夹下创建UserMapper这个接口,让这个接口继承BaseMapper ,注意泛型里面是要操作的实体类
package com.mybatis_plus.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mybatis_plus.pojo.User;
import org.springframework.stereotype.Repository;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
然后还要在springboot启动类上添加扫描注解,扫描这个mapper
注意:扫描包名千万别写错了,否则后面的代码全部白写
package com.mybatis_plus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
测试
在spring boot测试类里面编写测试类
查询
查询所有用户
package com.mybatis_plus;
import com.mybatis_plus.Mapper.UserMapper;
import com.mybatis_plus.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class DemoApplicationTests {
@Autowired
UserMapper userMapper;
@Test
void contextLoads() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
运行测试,得到结果(因为开启了日志,所以在控制台看到了sql这个执行过程,因为我之前测试过,所以表里的数据有些不一样)
控制台输出:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.4)
2022-03-12 14:27:54.068 INFO 9548 --- [ main] com.feng.MybatisplusApplicationTests : Starting MybatisplusApplicationTests using Java 1.8.0_202 on SmallWolfberry with PID 9548 (started by 冯小强 in E:\Java\springboot\mybatisplus)
2022-03-12 14:27:54.069 INFO 9548 --- [ main] com.feng.MybatisplusApplicationTests : No active profile set, falling back to 1 default profile: "default"
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Property 'mapperLocations' was not specified.
_ _ |_ _ _|_. ___ _ | _
| | |\/|_)(_| | |_\ |_)||_|_\
/ |
3.4.3
This primary key of "id" is primitive !不建议如此请使用包装类 in Class: "com.feng.entity.User"
2022-03-12 14:27:56.229 INFO 9548 --- [ main] com.feng.MybatisplusApplicationTests : Started MybatisplusApplicationTests in 2.544 seconds (JVM running for 3.685)
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@350a94ce] was not registered for synchronization because synchronization is not active
2022-03-12 14:27:56.449 INFO 9548 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-03-12 14:27:57.551 INFO 9548 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@488422671 wrapping com.mysql.cj.jdbc.ConnectionImpl@6fa13e6] will not be managed by Spring
==> Preparing: SELECT id,name,age,email,create_time,update_time FROM user
==> Parameters:
<== Columns: id, name, age, email, create_time, update_time
<== Row: 1, Jone, 18, test1@baomidou.com, null, null
<== Row: 2, Jack, 20, test2@baomidou.com, null, null
<== Row: 3, Tom, 28, test3@baomidou.com, null, null
<== Row: 4, Sandy, 21, test4@baomidou.com, null, null
<== Row: 5, Billie, 24, test5@baomidou.com, null, null
<== Total: 5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@350a94ce]
User(id=1, name=Jone, age=18, email=test1@baomidou.com, createTime=null, updateTime=null)
User(id=2, name=Jack, age=20, email=test2@baomidou.com, createTime=null, updateTime=null)
User(id=3, name=Tom, age=28, email=test3@baomidou.com, createTime=null, updateTime=null)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com, createTime=null, updateTime=null)
User(id=5, name=Billie, age=24, email=test5@baomidou.com, createTime=null, updateTime=null)
2022-03-12 14:27:57.631 INFO 9548 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2022-03-12 14:27:57.633 INFO 9548 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Process finished with exit code 0
除此之外,除了selectList()方法以外,mybatis-plus还带有很多其他的查询方法方法,在此不一一演示
,读者可以自行探索
使用Service层来调用服务:
准备工作:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fo0xsDA4-1647069309210)(E:/myblog/source/images/mybatis-plus%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B/image-20220312150929158.png)]
新建一个UserService类:
package com.feng.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.feng.entity.User;
public interface UserService extends IService<User> {
Boolean saveUser() throws Exception;
}
新建一个UserServiceImpl实现类:
package com.feng.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.entity.User;
import com.feng.mapper.UserMapper;
import com.feng.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public Boolean saveUser() throws Exception {
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>()
.eq(User::getId, 6)
.eq(User::getName, "ladidol")
.eq(User::getEmail, "599426945@qq.com");
User oldUser = baseMapper.selectOne(queryWrapper);
if (!StringUtils.isEmpty(oldUser)) {
throw new Exception();
}
User newUser = new User();
newUser.setAge(20);
newUser.setName("ladidol");
newUser.setEmail("ladidol@outlook.com");
return baseMapper.insert(newUser) > 0;
}
}
测试类中新添加方法:
package com.feng;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.feng.entity.User;
import com.feng.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class MybatisplusApplicationTests {
@Autowired
BaseMapper<User> baseMapper;
@Autowired
UserService userService;
@Test
void contextLoads() {
List<User> users = baseMapper.selectList(null);
users.forEach(System.out::println);
}
@Test
void saveTest() throws Exception {
userService.saveUser();
}
}
运行结果:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.4)
2022-03-12 15:06:39.024 INFO 14752 --- [ main] com.feng.MybatisplusApplicationTests : Starting MybatisplusApplicationTests using Java 1.8.0_202 on SmallWolfberry with PID 14752 (started by 冯小强 in E:\Java\springboot\mybatisplus)
2022-03-12 15:06:39.025 INFO 14752 --- [ main] com.feng.MybatisplusApplicationTests : No active profile set, falling back to 1 default profile: "default"
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Property 'mapperLocations' was not specified.
_ _ |_ _ _|_. ___ _ | _
| | |\/|_)(_| | |_\ |_)||_|_\
/ |
3.4.3
2022-03-12 15:06:41.136 INFO 14752 --- [ main] com.feng.MybatisplusApplicationTests : Started MybatisplusApplicationTests in 2.669 seconds (JVM running for 3.816)
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@790a251b] was not registered for synchronization because synchronization is not active
2022-03-12 15:06:41.387 INFO 14752 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-03-12 15:06:42.509 INFO 14752 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1134011961 wrapping com.mysql.cj.jdbc.ConnectionImpl@24841372] will not be managed by Spring
==> Preparing: SELECT id,name,age,email,create_time,update_time FROM user WHERE (id = ? AND name = ? AND email = ?)
==> Parameters: 6(Integer), ladidol(String), 599426945@qq.com(String)
<== Total: 0
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@790a251b]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@47406941] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1643565953 wrapping com.mysql.cj.jdbc.ConnectionImpl@24841372] will not be managed by Spring
==> Preparing: INSERT INTO user ( name, age, email, create_time, update_time ) VALUES ( ?, ?, ?, ?, ? )
==> Parameters: ladidol(String), 20(Integer), ladidol@outlook.com(String), null, null
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@47406941]
2022-03-12 15:06:42.596 INFO 14752 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2022-03-12 15:06:42.599 INFO 14752 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
代码自动生成器
mybatis-plus可以通过代码自动生成代码
需要导入如下依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
编写运行程序代码:
package com.feng;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
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(projectPath+"/src/main/java");
gc.setAuthor("Ladidol");
gc.setOpen(false);
gc.setFileOverride(false);
gc.setServiceName("%sService");
gc.setIdType(IdType.AUTO);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=true&useUnicode=true&characterEcoding=utf-8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("nihao123");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
PackageConfig pc = new PackageConfig();
pc.setModuleName("feng");
pc.setParent("com");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
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);
strategy.setLogicDeleteFieldName("deleted");
TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(createTime);
tableFills.add(updateTime);
strategy.setTableFillList(tableFills);
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
mpg.execute();
}
}
执行这个方法就会得到生成的代码了!
注意配置自己的数据库,另外,映射表名时注意对应自己表里面的字段。
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(createTime);
tableFills.add(updateTime);
strategy.setTableFillList(tableFills);
// 乐观锁 strategy.setVersionFieldName(“version”); strategy.setRestControllerStyle(true); strategy.setControllerMappingHyphenStyle(true); // localhost:8080/hello_id_2 mpg.setStrategy(strategy); mpg.execute(); //执行 } }
执行这个方法就会得到生成的代码了!
注意配置自己的数据库,另外,映射表名时注意对应自己表里面的字段。
|