整合Mybatis

本文详细介绍了如何在Spring Boot项目中整合Mybatis,包括引入Mybatis启动器依赖、设置配置以及通过映射文件和注解两种方式编写Sql语句。通过实例展示了如何创建映射文件、配置Mapper接口,并探讨了注解方式的使用及其优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

整合Mybatis

Mybatis是一款轻量级的ORM框架,他有灵活方便的特点,可以帮我们实现自定义的Sql语句,并且很方便地编写动态Sql,使用Spring Boot框架进行开发时也可以很轻松地整个Mybatis框架

引入依赖

使用Mybatis,首先需要引入Mybatis的启动器依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>

设置配置

之前如果使用Spring框架整合Mybatis,我们需要一个Mybatis的配置文件,现在我们只需要在Spring Boot的核心配置文件中配置Mybatis的配置就行了,如以下配置对应了此前Mybatis配置文件的几项配置

mybatis:
  configuration:
    cache-enabled: false #关闭一级缓存
    lazy-loading-enabled: true #开启懒加载
    map-underscore-to-camel-case: true #开启下划线和驼峰命名自动转换
  type-aliases-package: com.blackball.entity #配置需要别名的实体类包扫描

编写Sql语句

我有一个测试用的数据表,里面有一些数据

在这里插入图片描述

数据表对应的实体类如下

@Data
public class User {
    private Integer id;
    private Integer age;
    private String name;
    private String address;
}

测试使用Mybatis编写Sql将数据表中的数据查出来

使用Mybatis编写Sql语句有两种方法,一种是通过映射文件的方式,一种是通过注解的方式

编写映射文件

使用Sql映射文件,首先定义一个Mapper接口,然后在接口上标注@Mapper注解

@Mapper
public interface UserMapper {

    List<User> queryUsers();
}

在类路径下编写一个Sql映射文件,绑定Mapper接口和接口中的方法

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blackball.mapper.UserMapper">
    <select id="queryUsers" resultType="com.blackball.entity.User">
        select * from user
    </select>
</mapper>

然后在配置文件中配置映射文件的包扫描路径

mybatis:
  mapper-locations: classpath:mapper/*.xml

这样就可以使用Mapper接口操作数据库了

@SpringBootTest
class SpringDemoApplicationTests {

    @Autowired
    UserMapper userMapper;

    @Test
    void contextLoads() {
        List<User> users = userMapper.queryUsers();
        users.forEach(System.out::println);
    }

}

测试结果

在这里插入图片描述

如果觉得在每个Mapper接口都标注@Mapper注解太麻烦,可以使用@MapperScan注解来扫描Mapper接口所在的包下的所有Mapper接口,可以配置在配置类上或者主启动类上

@SpringBootApplication
@MapperScan("com.blackball.mapper")
public class SpringDemoApplication {

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

}

这么做会引起idea编译器报错,不过不影响正常运行

在这里插入图片描述

要消除这个报错,可以在Mapper接口上标注@Repository注解

注解绑定Sql语句

我们也可以使用注解的方式将Mapper接口中的方法和Sql语句绑定

对于增删改查语句,对应的有@Select @Update @Delete @Insert四种注解,将这些注解标注在方法上,在注解中编写Sql语句

@Mapper
public interface UserMapper {

    @Select("select * from user where id = #{id}")
    User queryUser(int id);
}

除此之外还有一个@Options注解,用于配置Sql语句

使用注解的方式,无需任何xml文件,也无需在配置文件中指定映射文件的包扫描路径,但是维护较为困难,一般简单的Sql语句使用注解的方式,复杂的使用编写映射文件的方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值