2021-06-21 SpringBoot之Mybatis-plus的整合

MybatisPlus作为Mybatis的增强工具,极大地简化了数据库操作。通过引入相关依赖和配置,可以实现自动注入和逻辑删除等功能。使用Lombok的注解优化了getter/setter和构造方法。在SpringBoot中,配合MapperScan注解和测试类,可以直接进行数据库操作。注意,当数据类型或列名不匹配时,仍可能出现错误。
摘要由CSDN通过智能技术生成

MybatisPlus作为mybaits的兄弟插件,提供了直接从JDBC链接数据库的功能,极大幅度的简化了繁杂的代码.

1.要使用Mybatis必须先从pm文件里

<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>Latest Version</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

引入相关的配置文件,

对于set和get以及无参,有参构造方法的简化我们使用LomBok插件提供的Date和

@NoArgsConstructor,@AllArgsConstructor注解来实现非常实用.

因为我一般是直接使用application.properties来操控SpringBoot的配置而且它的优先级也比较高,

我们在properties配置好了

spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/xiongyuhui?serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

数据源配置文件后再添加H2 数据库的相关配置:

# DataSource Config
spring:
  datasource:
    driver-class-name: org.h2.Driver
    schema: classpath:db/schema-h2.sql
    data: classpath:db/data-h2.sql
    url: jdbc:h2:mem:test
    username: root
    password: test

 要在启动类中添加@MapperScan注解后跟mapper文件夹的路径扫描到相应的mapper.xml配置文件,

可以在测试类中直接进行测试:

@SpringBootTest
public class SampleTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List<User> userList = userMapper.selectList(null);
        Assert.assertEquals(5, userList.size());
        userList.forEach(System.out::println);
    }

}

表逻辑删除的注解是

@TableLogic

使用此注解后表删除相关的语句调用后会成为修改语句,而且只对自动注入才有效

表如果列名和属性名不同的注解是

@TableField

可以修改不同属性名后台数据库的列名.

Mybatisplus通过CRUD接口封装Service接口,继承Mapper的基类,

/ 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);

需要注意的是尽管Mybatis优化了如此多的代码,但如果您的数据与数据库后台的数据基本类型或者列名不匹配的话还是会出错.

我们学完JAVA基础之后已经熟悉了八大数据类型,从Boot开始就可以使用Integer它们的大形态去赋值.

由于Boot采用了自动准装配封装的形式ajax在Boot中可以尽量避免使用./

自动填充.

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JavaEE-Web-阿熊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值