spring 搭建mybatis-plus
时间: 2023-09-23 18:12:34 浏览: 192
要搭建Spring框架集成MyBatis-Plus,首先需要使用Spring Boot框架作为基础,因为Spring Cloud离不开Spring Boot的基础。掌握在Spring Boot上集成MyBatis-Plus是一个很重要的技能。
以下是一个完整的示例代码,演示了如何在Spring Boot中集成MyBatis-Plus:
1. 创建一个启动类,使用@SpringBootApplication注解,并使用@MapperScan指定Mapper接口的扫描路径。该类的代码如下:
```java
@SpringBootApplication
@MapperScan("com.qf.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
```
2. 创建一个Mapper接口,例如UserMapper,使用MyBatis-Plus提供的通用Mapper接口,并定义相关的SQL操作。示例代码如下:
```java
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qf.entity.User;
public interface UserMapper extends BaseMapper<User> {
// 自定义SQL操作
// ...
}
```
3. 创建一个测试类,使用@SpringBottTest注解,并使用@Autowired注入UserMapper,通过调用UserMapper的方法来操作数据库。示例代码如下:
```java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.qf.entity.User;
import com.qf.mapper.UserMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestMybatisSpringBoot {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectList() {
List<User> users = this.userMapper.selectList(null);
for (User user : users) {
System.out.println(user);
}
}
}
```
通过以上步骤,就可以搭建一个基于Spring Boot的MyBatis-Plus项目,并且实现基本的数据库操作。在启动类中,使用@MapperScan注解指定Mapper接口的扫描路径,让Spring Boot能够自动加载这些Mapper接口。同时,在测试类中,使用@Autowired注入UserMapper,并通过调用UserMapper的方法来操作数据库。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [springboot集成mybatis-plus的demo基础搭建](https://download.csdn.net/download/zh_chong/83169592)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [Spring-mybatis-plus 整合spring](https://blog.csdn.net/m0_71255572/article/details/125695308)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文