SptringBoot整合MyBatis Plus

Spring Boot整合MyBatis Plus可以极大地简化MyBatis的使用,同时提供更加强大和灵活的功能。下面是一个简单的步骤说明如何整合Spring Boot和MyBatis Plus:

1. 添加依赖

首先,在pom.xml中添加MyBatis Plus的依赖:

<dependencies>  
    <!-- Spring Boot Starter Web -->  
    <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-web</artifactId>  
    </dependency>  
      
    <!-- MyBatis Plus -->  
    <dependency>  
        <groupId>com.baomidou</groupId>  
        <artifactId>mybatis-plus-boot-starter</artifactId>  
        <version>版本号</version>  
    </dependency>  
      
    <!-- MySQL Connector -->  
    <dependency>  
        <groupId>mysql</groupId>  
        <artifactId>mysql-connector-java</artifactId>  
        <scope>runtime</scope>  
    </dependency>  
      
    <!-- 其他依赖... -->  
</dependencies>

注意替换<version>版本号</version>为实际的MyBatis Plus版本号。

2. 配置数据源

application.propertiesapplication.yml中配置数据源:

# application.properties示例  
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC  
spring.datasource.username=root  
spring.datasource.password=your_password  
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

3. 创建实体类

根据数据库表结构创建对应的实体类,并使用MyBatis Plus提供的注解进行配置。例如:

import com.baomidou.mybatisplus.annotation.TableName;  
import com.baomidou.mybatisplus.annotation.IdType;  
import com.baomidou.mybatisplus.annotation.Id;  
import java.io.Serializable;  
  
@TableName("user")  
public class User implements Serializable {  
      
    @Id  
    @IdType(type = IdType.AUTO)  
    private Long id;  
    private String name;  
    private Integer age;  
    private String email;  
      
    // getter和setter方法...  
}

4. 创建Mapper接口

创建一个继承自BaseMapper<T>的Mapper接口:

import com.baomidou.mybatisplus.core.mapper.BaseMapper;  
import org.apache.ibatis.annotations.Mapper;  
  
@Mapper  
public interface UserMapper extends BaseMapper<User> {  
    // 自定义方法可以在这里添加  
}

5. 使用Mapper

在Service或Controller中注入Mapper,并调用其方法进行数据库操作。例如:

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RestController;  
  
@RestController  
public class UserController {  
      
    @Autowired  
    private UserMapper userMapper;  
      
    @GetMapping("/users")  
    public List<User> getAllUsers() {  
        return userMapper.selectList(null);  
    }  
}

6. 启动应用

启动Spring Boot应用,然后你就可以通过访问定义的接口来进行数据库操作了。

以上就是一个简单的Spring Boot整合MyBatis Plus的步骤。你可以根据自己的需求进行更详细的配置和扩展。例如,你可以配置分页插件、使用LambdaQueryWrapper进行条件查询等。详细的使用方法可以参考MyBatis Plus的官方文档。

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值