MyBatis-Plus整合SpringBoot及使用

MyBatis-Plus是一种增强版的MyBatis框架,它简化了CRUD操作,并提供了一系列功能来简化MyBatis的使用和提高开发效率。整合MyBatis-Plus至Spring Boot项目可以进一步提升开发效率和项目的规模化。

以下是整合MyBatis-Plus到Spring Boot项目以及它的基本用法:

1. 添加依赖

在Spring Boot项目的 pom.xml中添加MyBatis-Plus的依赖。确保也添加了数据库连接相关的依赖,如MySQL驱动。

<dependencies>
    <!-- MyBatis-Plus -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>最新版本号</version>
    </dependency>

    <!-- 数据库驱动,以下是MySQL的例子 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

    <!-- 其他Spring Boot依赖... -->
</dependencies>
 
 

2. 配置数据源

在 application.properties或 application.yml文件中配置数据库连接信息。

# application.properties 示例
spring.datasource.url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=数据库用户名
spring.datasource.password=数据库密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
 
 

3. 配置MyBatis-Plus

在Spring Boot的配置类中添加 @MapperScan注解来扫描Mapper接口。

@SpringBootApplication
@MapperScan("com.example.project.mapper") // 指向你的mapper接口所在的包
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
 
 

4. 编写实体类

创建与数据库表映射的实体类。

@Data
@TableName("user") // 数据库中的表名
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    // 其他字段...
}
 
 

5. 编写Mapper接口

创建Mapper接口,继承 BaseMapper接口。MyBatis-Plus会自动提供多种方法。

public interface UserMapper extends BaseMapper<User> {
    // 自定义的其他方法
}
 
 

6. 使用

在Service层或控制器中注入Mapper,并调用MyBatis-Plus提供的方法。

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<User> findAll() {
        return userMapper.selectList(null); // 查询所有用户
    }

    public User findById(Long id) {
        return userMapper.selectById(id); // 根据ID查询用户
    }

    // 其他业务方法...
}
 
 

7. 进阶使用

MyBatis-Plus提供了许多额外的功能,如ActiveRecord模式、分页插件、条件构造器以及代码生成器等。

整合MyBatis-Plus到Spring Boot无疑可以提升开发的便利性和效率。通过它提供的各种快捷操作,可以减少大量的重复代码,使得开发者可以将更多的精力放在业务逻辑的实现上。

posted @ 2025-05-25 10:06  晃悠人生  阅读(115)  评论(0)    收藏  举报