SpringBoot 3.1.10 整合Mybatis-plus(快速学会)
在Spring Boot 3.1.10中整合MyBatis-Plus可以通过以下步骤进行:
- 在
pom.xml
中添加MyBatis-Plus的依赖:
<dependencies>
<!-- 其他依赖... -->
<!-- MyBatis-Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</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
- 创建实体类对应数据库表:
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("your_table")
public class YourEntity {
// 实体类属性和数据库字段映射
}
- 创建Mapper接口:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface YourEntityMapper extends BaseMapper<YourEntity> {
// 此接口会继承CRUD操作
}
- 在Spring Boot启动类上添加
@MapperScan
注解,指定Mapper接口所在的包:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.yourpackage.mapper") // 指定Mapper接口的包路径
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
完成以上步骤后,你就可以在你的服务中注入YourEntityMapper
并使用MyBatis-Plus提供的CRUD操作了。
示例代码:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class YourService {
private final YourEntityMapper yourEntityMapper;
@Autowired
public YourService(YourEntityMapper yourEntityMapper) {
this.yourEntityMapper = yourEntityMapper;
}
public List<YourEntity> getAllEntities() {
return yourEntityMapper.selectList(null); // 获取所有记录
}
}
以上代码展示了如何在Spring Boot 3.1.10项目中使用MyBatis-Plus进行数据库操作。
评论已关闭