MybatisPlus----入门案例

引入相关依赖依赖

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</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>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>

安装lombok插件
lombok常用注解:
@Date提供类所有属性的getting和setting方法以及无参构造器
@Setter/@Getter提供setting/getting方法
@NoArgsConstructor/@AllArgsConstructor提供有参/全参构造方法
....
编写配置文件

spring:
# 配置数据源信息
  datasource:
# 配置数据源类型
    type: com.zaxxer.hikari.HikariDataSource
# 配置连接数据库信息
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf- 8&useSSL=false
    username: root
    password: 123456
  # 配置MyBatis日志
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

启动类配置
需要额外添加@MapperScan扫描指定包下的接口,并将它们作为Mapper接口注册到Spring容器中。

@SpringBootApplication
@MapperScan("com.aaa.mybatisplus.mapper")
public class MybatisplusApplication {

public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args); }

}

添加实体
使用@Date注解简化实体类的创建

@Data //lombok注解
public class User {

private Long id;
private String name;
private Integer age;
private String email;
}

添加mapper
继承Mybatis-Plus提供的BaseMapper,进行基本的CRUD操作

public interface UserMapper extends BaseMapper<User> {
}

测试

@SpringBootTest
public class MybatisPlusTest {

@Autowired
private UserMapper userMapper;

@Test
public void testSelectList(){
//selectList()根据MP内置的条件构造器查询一个list集合,null表示没有条件,即查询所有
userMapper.selectList(null).forEach(System.out::println);
}

}

spring框架测试类与springboot测试类的对比
spring框架编写测试类:
1.在测试类上使用@RunWith注解测试运行器。
2.使用@ContextConfiguration注解指定Spring的配置(可以是XML配置文件,也可以是配置类)。
3.装载需要的Bean并完成JUnit标签@Test注解的测试方法。

@RunWith(SpringJUnit4ClassRunner.class) //运行器注解
@ContextConfiguration(locations=“classpath:cn/osxm/ssmi/chp6/applicationContext.xml”)//配置
public class SpringTest { //测试类
@Autowired //自动装载注解
private HelloService helloService;
@Test //测试方法注解
public void hello() { //测试方法

springboot编写测试:
利用@SpringBootTest实现启动 Spring 应用上下文,加载完整的 Spring Boot 应用配置

@SpringBootTest
public class MybatisPlusTest {

    @Autowired
    private UserMapper userMapper;
posted @ 2025-03-26 22:31  茴香儿  阅读(5)  评论(0)    收藏  举报