SpringBoot3整合Mybatis plus
Spring Boot 3整合MyBatis Plus的步骤如下:
- 在
pom.xml
中添加MyBatis Plus和数据库驱动的依赖。
<dependencies>
<!-- MyBatis Plus -->
<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>
<version>8.x.x</version>
</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;
public interface YourMapper extends BaseMapper<YourEntity> {
// 自定义操作
}
- 在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")
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
- 使用MyBatis Plus提供的方法进行数据库操作。
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class YourService {
@Autowired
private YourMapper yourMapper;
public YourEntity getById(Long id) {
return yourMapper.selectById(id);
}
public void insert(YourEntity entity) {
yourMapper.insert(entity);
}
public void update(YourEntity entity) {
yourMapper.updateById(entity);
}
public void deleteById(Long id) {
yourMapper.deleteById(id);
}
public List<YourEntity> listByCondition(String condition) {
QueryWrapper<YourEntity> queryWrapper = ne
评论已关闭