目录
一、mybatis-plus 简介
特性
二、支持数据库:
三、 开发实例
1. 引入依赖:
2. 参数配置application.yml
3. 在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:
4. 编写实体类 User.java(此处使用了 Lombok (opens new window)简化代码)
5. 编写 Mapper 包下的 UserMapper接口
6. 测试
四、 多数据源
1. 约定
2. 配置数据源
3. 使用 @DS 切换数据源
mybatis-plus 是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考MyBatis-Plus官网
MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
com.baomidou
mybatis-plus-boot-starter
最新版本
com.h2database
h2
runtime
spring:
datasource:
driver-class-name: org.h2.Driver
schema: classpath:db/schema-h2.sql
username: root
password: test
sql:
init:
schema-locations: classpath:db/schema-h2.sql
data-locations: classpath:db/data-h2.sql
@MapperScan
注解,扫描 Mapper 文件夹:@SpringBootApplication
@MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
User.java
(此处使用了 Lombok (opens new window)简化代码)@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
UserMapper
接口public interface UserMapper extends BaseMapper {
}
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}
1. 本框架只做 切换数据源 这件核心的事情,并不限制你的具体操作,切换了数据源可以做任何CRUD。
2.配置文件所有以下划线 _ 分割的数据源 首部 即为组的名称,相同组名称的数据源会放在一个组下。
3. 切换数据源可以是组名,也可以是具体数据源名称。组名则切换时采用负载均衡算法切换。
4. 默认的数据源名称为 master ,你可以通过 spring.datasource.dynamic.primary 修改。
5. 方法上的注解优先于类上注解。
6. DS支持继承抽象类上的DS,暂不支持继承接口上的DS。
2. 使用方法
com.baomidou
dynamic-datasource-spring-boot-starter
${version}
spring:
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
master:
url: jdbc:mysql://xx.xx.xx.xx:3306/dynamic
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
slave_1:
url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
slave_2:
url: ENC(xxxxx) # 内置加密,使用请查看详细文档
username: ENC(xxxxx)
password: ENC(xxxxx)
driver-class-name: com.mysql.jdbc.Driver
#......省略
#以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2
@Service
@DS("slave")
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public List selectAll() {
return jdbcTemplate.queryForList("select * from user");
}
@Override
@DS("slave_1")
public List selectByCondition() {
return jdbcTemplate.queryForList("select * from user where age >10");
}
}