springboot整合mybatis-plus

springboot整合mybatis-plus

简介

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

实战

1.引入依赖

        <!-- mybatisPlus 核心库 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.4.2</version>
        </dependency>

2.使用插件

以下配置可根据项目需要配置,初学者学习可跳过本步骤。

/**
 * @author gf
 * @date 2022/7/18
 */
@Configuration
//主要是扫描到mapper包下的接口交给spring管理,我这里在启动类上添加过了,这里就不加了
public class MybatisPlusDatasourceConfig {


    /**
     * 新的分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 新的分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 乐观锁插件
        /*当要更新一条记录的时候,希望这条记录没有被别人更新(在实体类的字段上加上@Version注解)*/
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        // 防全表更新与删除插件
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        return interceptor;
    }

    @Bean
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource)
            throws Exception {
        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);

        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.addInterceptor(mybatisPlusInterceptor());
        sessionFactory.setConfiguration(configuration);

        //mybatis 数据库字段与实体类属性驼峰映射配置
        sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sessionFactory.getObject();
    }

}

3.创建实体

@TableName(value = “user_info”)对应数据库中的表名

/**
 * @author gf
 * @date 2022/7/19
 */
@Data
@TableName(value = "user_info")
public class UserInfo {

    private String id;

    private String name;

    private String sex;

    private String email;

}

4.Mapper 包下编写 UserMapper接口

/**
 * @author gf
 * @date 2022/7/19
 */

@Repository
public interface UserMapper extends BaseMapper<UserInfo> {
}

5.启动类上配置扫描Mapper包的注解

@MapperScan(“com.tomato.tomatocenter.mapper”)为UserMapper的包路径

@SpringBootApplication
@MapperScan("com.tomato.tomatocenter.mapper")
public class TomatoCenterApplication {

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

}

6.编写测试类测试

@SpringBootTest
class TomatoCenterApplicationTests {

    @Autowired
    private UserMapper userMapper;


    @Test
    void contextLoads() {
        System.out.println(("----- 测试方法 ------"));
        UserInfo userInfo = userMapper.selectById("**");
        System.out.println("----- 测试结果 ------"+userInfo);
    }

}

测试结果:


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.6.9)

2022-07-19 11:39:56.093  INFO 15800 --- [           main] c.t.t.TomatoCenterApplicationTests       : Starting TomatoCenterApplicationTests using Java 1.8.0_181 on ISS490002001977 with PID 15800 (started by issuser in D:\clone\tomato-center)
2022-07-19 11:39:56.095  INFO 15800 --- [           main] c.t.t.TomatoCenterApplicationTests       : The following 1 profile is active: "dev"
 _ _   |_  _ _|_. ___ _ |    _ 
| | |\/|_)(_| | |_\  |_)||_|_\ 
     /               |         
                        3.4.2 
2022-07-19 11:40:00.317  INFO 15800 --- [           main] c.t.t.TomatoCenterApplicationTests       : Started TomatoCenterApplicationTests in 4.604 seconds (JVM running for 6.109)
----- 测试方法 ------
2022-07-19 11:40:00.804  INFO 15800 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-07-19 11:40:01.407  INFO 15800 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
----- 测试结果 ------UserInfo(id=1001211111000020001, name=abc, sex=null, email=u.fjnglrqmo@tmtwbafh.gi)
2022-07-19 11:40:01.556  INFO 15800 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2022-07-19 11:40:01.839  INFO 15800 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
Disconnected from the target VM, address: '127.0.0.1:63590', transport: 'socket'

Process finished with exit code 0

注:详情请参考 mybatis-plus使用指南

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值