SpringBoot整合MybatisPlus

1. 导入MySQL连接和MybatisPlus依赖

注意:5.x版本的MySQL连接对应5.x版本的MySQL;8.x版本的MySQl连接要对应8.x版本的MySQL;否则会出现坑!我本地MySQL版本是8.x因此要选择8.x的数据库连接。

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.22</version>
</dependency>

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3</version>
</dependency>

2. application.yml文件配置数据库

spring:
  datasource:
    username: [用户名]
    password: [密码]
    url: jdbc:mysql://localhost:3306/[你的数据库名]?useSSL=false&charsetEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true 
    driver-class-name: com.mysql.cj.jdbc.Driver 

说明:

  • 不使用ssl连接:useSSL=false
  • 设置编码方式:charsetEncoding=utf8
  • 设置时区:serverTimezone=Asia/Shanghai
  • 允许客户端从服务器获取公钥:allowPublicKeyRetrieval=true

  • MySQL8使用的是:com.mysql.cj.jdbc.Driver驱动类;MySQL5.x使用的是com.mysql.jdbc.Driver驱动类

3. 在启动类上配置Mapper的扫描路径

@MapperScan("com.xxx.mapper")
@SpringBootApplication
public class XXXApplication {
    public static void main(String[] args) {
        SpringApplication.run(XXXApplication.class, args);
    }
}

// 如果有多个mappe路径可以这样配置
@MapperScans({
        @MapperScan("com.model1.mapper"),
        @MapperScan("com.model2.mapper")
})

4. 准备数据库表

CREATE TABLE `users` (
	`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_cs_0900_ai_ci',
	`age` INT(10) UNSIGNED NOT NULL DEFAULT '0',
	`sex` BIT(1) NOT NULL DEFAULT 'b\'0\'',
	`address` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_cs_0900_ai_ci',
	PRIMARY KEY (`id`) USING BTREE
)
COLLATE='utf8mb4_cs_0900_ai_ci'
ENGINE=InnoDB
;

5. 编写Entity,Mapper,和Service

  • UsersEntity
@Data
public class UsersEntity {
    private Long id;
    private String name;
    private Integer age;
    private Boolean sex;
    private String address;
}
  • UserMapper
@Repository
public interface UsersMapper extends BaseMapper<UsersEntity> {
}
  • Service/impl
public interface UsersService {
}

@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, UsersEntity> implements UsersService {
}

6. 测试Mapper和Service

@SpringBootTest
public class TestUsers {

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private UsersServiceImpl usersService;

    @Test
    void testMapper() {
        System.out.println(usersMapper.selectById(1L));
    }

    @Test
    void testService() {
        System.out.println(usersService.getById(1L));
    }
}

测试结果:
测试结果截图

说明:

mapper和service都是MybatisPuls提供的内置Sql操作;

mapper是sql层面的细粒度sql操作,而service是偏向业务层面的提供了更为强大的增删改查业务操作。

Mapper:
Mapper接口的主要方法

Service:
Service接口的主要方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值