1引入pom依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 模板引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 熱部署、測試 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 驅動、連接池 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${alibaba.druid}</version>
</dependency>
<!-- MP -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
2 配置連接池
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.20.40:3306/ca_ct_business?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: 123456
3編寫Mapper(繼承BaseMapper即可獲得基礎CRUD操作)
public interface BusinessMapper extends BaseMapper<BusinessEntity> {
}
4使用註解進行Mapper掃描
@MapperScan("com.ca.ct.console.mapper")
5依賴注入使用即可
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class BaseTest {
@Autowired
private BusinessMapper busiMapper;
@Test
public void testBusiMapper() {
System.out.println(busiMapper.selectById(1));
}
}
6可使用MP中的擴展類ServiceImpl(ServiceImpl中具體還是使用的BaseMapper)
@Service
public class BusinessService extends ServiceImpl<BusinessMapper, BusinessEntity> {
}
@Autowired
private BusinessService busiService;
@Test
public void testBusiMapper() {
BusinessEntity oneById = busiService.getOne(new QueryWrapper<BusinessEntity>().eq("ID", 1));
System.out.println(oneById);
}
7擴展類IService和BaseMapper區別
①BaseMapper是通用CRUD的簡單封裝,爲Mybatis-Plus在啓動時自動解析實體表關係映射轉換爲Mybatis內部對象注入容器。其功能有限,諸如批量新增等查用接口需自己再封裝。
②擴展類IService是BaseMapper的增強,提供了諸如BaseMapper沒有的批插入、保存或新增、批量更新等,且包含了大量Java1.8支持的默認實現。企業場景使用時,可在Mapper基礎上封裝Dao類,使Dao類繼承IService的實現類ServiceImpl實現功能增強。這裏IService中Service單詞不等於項目中Service服務層單詞中的Service。