小编最近工作项目里面用到了 mybatis-plus,比自己手写sql,方便太多。
比较之前项目的 mybatis,也快捷不少。这里总结了一下,springboot 集成 mybatis-plus,
完整步骤。
1,添加 mybatis-plus-extension依赖。
com.baomidou mybatis-plus-extension 3.2.0
2,application.properties 文件中,新增数据库连接信息。
spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521/SECRETARYDB spring.datasource.username=admin spring.datasource.password=123456 spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
3,编写mybatisplus数据源及包扫描配置文件,这一步也是集成mybatis的核心步骤,
通过配置文件,将用户从原始的jdbc访问中解放出来,用户只需要定义操作的sql语句,
无须关注底层的jdbc操作,通过面向对象的方式进行持久化操作。
mybatis中常见的对象有 SqlSessionFactory和SqlSession。
@Configuration
@MapperScan(basePackages = MybatisPlusDataSourceConfig.PACKAGE_DAO, sqlSessionFactoryRef = "sqlSessionFactory")
public class MybatisPlusDataSourceConfig {
// dao层所在路径
static final String PACKAGE_DAO = "com.cmbchina.mapper";
// *mapper.xml文件所在路径
static final String MAPPER_LOCATION = "classpath:mybatis/mapper
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
@Bean
public OracleKeyGenerator oracleKeyGenerator(){
return new OracleKeyGenerator();
}
}
4,编写entity,实现Serializable接口(方便序列化和反序列化),
声明 serialVersionUID(保证反序列化不会出现异常)
COXDBO.BILL_ConFIG 是查询数据所有数据库下具体表格。
@TableName("COXDBO.BILL_CONFIG")
public class SwitchConfig implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "OWNER_APP", type = IdType.INPUT)
private String ownerApp;
@TableId(value = "CONFIG_KEY", type = IdType.INPUT)
private String configKey;
private String configValue;
private String remark;
private String runtimeConfig;
//todo... get set 方法省略。。。
}
5,编写mapper层,继承baseMapper。
@Mapper @Repository public interface MyBatisPlusMapper extends baseMapper{}
6,编写xml文件。
7,编写service层,继承IService。
public interface MyBatisPlusService extends IService{}
8,编写serviceImpl层,实现service层,继承ServiceImpl。
@Service @Transactional(rollbackFor = Exception.class) public class MyBatisPlusServiceImpl extends ServiceImplimplements MyBatisPlusService {}
9,编写controller层。
@Api(tags = "测试mybatisplus接口 API")
@RestController
@RequestMapping("/mybatisTest")
public class MyBatisPlusController {
@Resource
private MyBatisPlusService myBatisPlusService;
@ApiOperation("获取列表数据")
@PostMapping("/getList")
public List getById() {
QueryWrapper wrapper = new QueryWrapper();
List list = myBatisPlusService.list(wrapper);
return list;
}
}
10,测试结果,浏览器输入: http://localhost:8080/mybatisTest/getList 即可调用接口,查询数据。
即可。



