MybatisPlus入门
MybatisPlus基本使用
假设你已经建立数据表
在SpringBoot中引入相关依赖:
<!-- SpringBoot单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Web开发场景启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringBoot场景启动器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<!-- lombok 简化实体类的编写-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<!-- MybatisPlus依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
配置数据库信息:
在application.yaml
中配置:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
password: zqh123
username: root
driver-class-name: com.mysql.cj.jdbc.Driver
编写Mapper接口
目录:com.blog.qh.mybatisplus.mapper.UserMapper
UserMapper继承MybatisPlus的BaseMapper接口,里面是对单表的CURD操作。
Spring动态生成UserMapper接口代理对象
package com.blog.qh.mybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.blog.qh.mybatisplus.pojo.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends BaseMapper<User> {
}
添加Mapper包扫描
在SpringBoot启动入口类中:
package com.blog.qh.mybatisplus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.blog.qh.mybatisplus.mapper")
public class MyBatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MyBatisPlusApplication.class,args);
}
}
测试
package com.blog.qh.mybatisplus;
import com.blog.qh.mybatisplus.mapper.UserMapper;
import com.blog.qh.mybatisplus.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
public class TestMybatisPlus {
@Autowired
UserMapper userMapper;
@Test
public void TestAllEle() {
// 这个参数是条件查询,我们不需要条件筛选,参数为null查全部
List<User> users = userMapper.selectList(null);
for(User user : users) {
System.out.println(user);
}
}
}
文章目录
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
评论已关闭