springboot 整合 mybatis-plus
    		       		warning:
    		            这篇文章距离上次修改已过420天,其中的内容可能已经有所变动。
    		        
        		                
                整合步骤:
- 添加依赖:在pom.xml中添加Spring Boot Starter和MyBatis-Plus的依赖。
<dependencies>
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!-- MyBatis-Plus Starter -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.x.x</version> <!-- 替换为实际版本号 -->
    </dependency>
    <!-- 数据库驱动,以MySQL为例 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>- 配置数据库信息:在application.properties或application.yml中配置数据库连接信息。
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver- 创建实体类和Mapper接口:实体类对应数据库表,Mapper接口用于数据库操作。
// User.java (实体类)
@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
 
// UserMapper.java (Mapper接口)
@Mapper
public interface UserMapper extends BaseMapper<User> {
    // 其他自定义数据库操作方法
}- 启动类:添加@MapperScan注解扫描Mapper接口。
@SpringBootApplication
@MapperScan("com.yourpackage.mapper") // 替换为实际包路径
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}- 使用MyBatis-Plus提供的CRUD操作:在Service中注入UserMapper,使用selectList、insert等方法。
// UserService.java
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    
    public List<User> getAllUsers() {
        return userMapper.selectList(null); // 获取所有用户
    }
    
    public void addUser(User user) {
        userMapper.insert(user); // 添加用户
    }
}以上步骤可以实现Spring Boot整合MyBatis-Plus的基本操作。根据实际需求,可能还需要进行额外配置,如分页插件配置、全局配置、自定义SQL等。
评论已关闭