Mybatis-Plus学习记录
1. 创建一个SpringBoot项目
1.1添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</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>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!-- 阿里数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
<!-- 模板引擎 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>
1.2 在application.yml配置文件中添加MySQL数据库的相关配置
spring:
datasource:
# driver-class-name: com.mysql.cj.jdbc.Driver
# url: jdbc:mysql://localhost:3306/jtdb?serverTimezone=UTC
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.p6spy.engine.spy.P6SpyDri`
url: jdbc:p6spy:mysql://localhost:3306/jtdb?serverTimezone=UTC
password: 123456
username: root
1.3 在spring boot启动类中添加@MapperScan注解,扫描Mapper文件夹:
@SpringBootApplication
@MapperScan("com.cg.mapper") //扫描mapper
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
2. 数据库准备
2.1 创建一个user表
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NOT NULL COMMENT '姓名',
age INT(11) NULL COMMENT '年龄',
gender TINYINT(2) NOT NULL COMMENT '性别',
PRIMARY KEY (id)
);
2.2 插入数据
INSERT INTO user (id, name, age, gender ) VALUES
(1, 'xiaoming', 11, 1),
(2, 'xiaoming1', 13, 0),
(3, 'xiaoming2', 20, 1);
3.测试准备
3.1 创建一个user实体类
package com.cg.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Builder;
import lombok.Data;
@Data
@TableName("user")
@Builder
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private Integer gender;
}
3.2 编写Mapper包下的UserMapper接口
package com.cg.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cg.entity.OrderVo;
import com.cg.entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
这里注意添加@Mapper注解,以及启动类添加@MapperScan(“xxx”)注解
4.测试
4.1 添加测试类
@SpringBootTest
class MybatisPlusApplicationTest {
@Autowired
UserMapper userMapper;
@Autowired
UserService userService;
@Test
void contextLoads() {
List<User> userList = userMapper.selectList(null);
userList .forEach(user-> System.out.println(user.toString()));
}
}
5.MybatisPlus增删改查
5.1 增加
@Test
void contextLoads() {
/**
使用mapper层查询数据 在mapper中只封装了insert()方法
*/
User user = new User();
user.setAge(10);
user.setGender(1);
user.setName("xiaoming");
userMapper.insert(user);
// 这service中封装的插入方法 save
boolean isSuccess = userService.save(user);
}
5.2 删除
// Mapper层删除功能
// 根据主键id删除数据(直接传id)
int count = userMapper.deleteById(9L);
System.out.println("删除了:"+ count);
// 根据主键id删除(传实体类)
User user = new User();
user.setId(8L);
int count = userMapper.deleteById(user);
System.out.println("删除了:"+ count);
// 根据主键id批量删除数据
List<Long> ids = new ArrayList<>();
ids.add(1L);
ids.add(2L);
delete from user where id in (1,2);
userMapper.deleteBatchIds(ids);
// 通过构造Wrapper构造器删除
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.eq("name","xiaoming1");
wrapper.eq("age",11);
delete from user where (name="xiaoming1" and age = 11);
userMapper.delete(wrapper);
// lambda表达式删除
userMapper.delete(new QueryWrapper<User>()
.lambda()
.eq(User::getName, "xiaoming1")
.eq(User::getAge,11)
);
5.3 修改
// mapper层
User user = User.builder()
.name("xiaoxiaoming")
.id(5L)
.gender(0)
.build();
int count = userMapper.updateById(user);
System.out.println("更新了:" + count);
// 通过wrapper进行更新
User user = User.builder().name("hahah").gender(0).build();
UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper.eq("age",13);
int count = userMapper.update(user,userUpdateWrapper);
// service层
UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper.set("name","xixix");
userUpdateWrapper.eq("id",2L).eq("age",13);
userService.update(userUpdateWrapper);
5.4 查询
// mapper层
// 根据 id查询数据
User user = userMapper.selectById(2L);
System.out.println(user.toString());
// 通过构造wrapper条件查询一条数据
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
// 设置查询字段;仅查询name id字段
queryWrapper.select("id","name");
// 添加查询条件
queryWrapper.eq("id",2L);
User user1 = userMapper.selectOne(queryWrapper);
System.out.println(user1.toString());
//根据id批量查询
List<User> userList = userMapper.selectBatchIds(Arrays.asList(5L,6L,7L));
// 通过Wrapper组装查询条件,查询全部数据
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
// 设置查询字段;仅查询name id字段
queryWrapper.select("id","name");
// 添加查询条件
queryWrapper.eq("age",30);
List<User> users = userMapper.selectList(queryWrapper); // 查询全部数据
// 根据columnMap设置查询条件
Map<String,Object> colMap = new HashMap<>();
colMap.put("name","xixix");
colMap.put("age",13);
//select * from user where name="xixix" and age=13;
List<User> userList1 = userMapper.selectByMap(colMap); // 使用map构造查询
// 根据wrapper条件,查询记录总数
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name","xixi").eq("age",13);
long count = userMapper.selectCount(queryWrapper); // 获取总量
// service
User user = userService.getById(5L); // 根据id获取数据
// 通过Wrapper条件查询一条数据,当结果出现多条数据是会抛出异常
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name","xixi").eq("id",5L);
// select * from user where id= 5 and name = "xixi"
User user1 = userService.getOne(queryWrapper);
// 通过list开头的方法来查询多条数据
// 条件查询
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name","xixi").eq("id",5L);
select * from user where id= 5 and name = "xixi"
List<User> users = userService.list(queryWrapper);
// 根据id列表查询数据
select * from user where id in(5,6)
List<User> userList = userService.listByIds(Arrays.asList(5L,6L));
// 通过map构造查询条件
Map<String,Object> cloMap = new HashMap<>();
cloMap.put("name","xixi");
cloMap.put("age",13);
//select * from user where age= 13 and name = "xixi"
List<User> userList1 = userService.listByMap(cloMap);
6. MybatisPlus代码生成器
package com.cg.util;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import java.util.ArrayList;
import java.util.List;
public class CodeGenerator {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/jtdb?serverTimezone=UTC";
String username = "root";
String password = "123456";
String module = ""; // 表示项目的模块名称
String outPath = System.getProperty("user.dir") + "/" + module + "/src/main/java"; // 文件输出路径
String parent = "com.gcxy"; // 父包的名称
String moduleName = ""; // 模块名称
String entity = "entity";
String mapper = "mapper";
String service = "service";
String serviceImpl = "service.Impl";
String controller = "controller";
String mapperXml = "mapper.xml";
List<String> tables = new ArrayList<>();
tables.add("account");
tables.add("phone");
tables.add("dep");
tables.add("stu");
FastAutoGenerator.create(url, username, password)
// 全局配置
.globalConfig(builder -> {
builder.author("huangwei") // 设置作者
// .enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir(outPath) // 指定输出目录
.disableOpenDir(); // 生成后不打开目录
})
// 包配置
.packageConfig(builder -> {
builder.parent(parent) // 设置父包名
.moduleName(moduleName) // 设置父包模块名
.entity(entity)
.mapper(mapper)
.service(service)
.serviceImpl(serviceImpl)
.controller(controller)
.xml(mapperXml);
})
// 策略配置
.strategyConfig(builder -> {
builder.addInclude(tables) // 设置需要生成的表名
// .addTablePrefix("t_", "c_"); // 设置过滤表前缀
.entityBuilder() // 开启生成实体类
.enableLombok() // 开启lombok模型
.mapperBuilder() // 开启生成mapper
.superClass(BaseMapper.class)
// .enableMapperAnnotation() // 开启mapper注解
.formatMapperFileName("%sMapper") // 格式化mapper名称
.formatXmlFileName("%sMapper") // 格式化xml的名称
.serviceBuilder() // 开启生成service
.formatServiceFileName("%sService") //格式化service接口文件名称
.formatServiceImplFileName("%sServiceImpl")
.controllerBuilder() //开启controller生成
.formatFileName("%sController")
.enableRestStyle();
})
.templateEngine(new VelocityTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}