一、引言
MyBatis-Plus官网 https://mybatis-plus.com
MyBatis-Plus(简称 MP)是一个 在MyBatis的增强工具 ,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。- - -引自官网 框架结构
二、环境搭建
1、创建数据库并新建user表
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
bir timestamp NULL DEFAULT NULL COMMENT '出生日期',
PRIMARY KEY (id)
);
2、 使用Spring Initializer快速初始化一个 Spring Boot 工程
3、添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
</dependencies>
4、配置
在 application.yml 配置文件中添加如下配置:
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis-plus?characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
logging:
level:
root: info
com.uos.dao: debug
注意: ? ? 1. 此时无需添加mybatis的相关配置; ? ? 2. 如果mysql是5.x以上版本,请将driver-class-name 设置为com.mysql.cj.jdbc.Driver ,否则后续测试时会报错!
在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:
@SpringBootApplication
@MapperScan("com.uos.dao")
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
5、编码
编写实体类 User.java(此处使用了 Lombok简化代码)
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Accessors(chain = true)
public class User {
private String id;
private String name;
private Integer age;
private Date bir;
}
编写DAO类 UserDAO.java
public interface UserDAO extends BaseMapper<User> {
}
6、开始使用
添加测试类,进行功能测试:
@SpringBootTest
public class TestUserDao {
@Autowired
private UserDAO userDAO;
@Test
public void testFindAll(){
List<User> users = userDAO.selectList(null);
users.forEach(user -> System.out.println("user=" + user));
}
}
三、常用注解
1、@TableName 表名注解
@TableName(value = "t_user")
注意:该注解是写在实体类名的上方,默认将类名作为表名。
2、 @TableId 主键注解
@TableId(value = "id", type = IdType.AUTO)
private String id;
3、 @TableField 字段注解(非主键)
@TableField(value = "username")
private String name;
private Integer age;
private Date bir;
@TableField(exist = false)
private String email;
四、常见方法使用
1、查询方法
@Test
public void testFindAll(){
List<User> users = userDAO.selectList(null);
users.forEach(user -> System.out.println("user=" + user));
}
@Test
public void testFindById(){
User user = userDAO.selectById("2");
System.out.println(user);
}
@Test
public void testFind(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.ge("age", 22);
List<User> users = userDAO.selectList(queryWrapper);
users.forEach(user -> System.out.println("user=" + user));
}
@Test
public void testFindLike(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.likeRight("username","张");
List<User> users = userDAO.selectList(queryWrapper);
users.forEach(user -> System.out.println("user=" + user));
}
@Test
public void testFindByPage(){
IPage<User> page = new Page(1,2);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age", 22);
IPage<User> userIPage = userDAO.selectPage(page, queryWrapper);
long total = userIPage.getSize();
System.out.println("记录数:" + total);
userIPage.getRecords().forEach(user -> System.out.println(user));
}
注意:分页查询插件需要添加如下配置方可生效! 创建config 包,在该包中创建MybatisPlusConfig 类
@EnableTransactionManagement
@Configuration
@MapperScan("com.uos.dao")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}
2、添加方法
@Test
public void testSave(){
User user = new User();
user.setName("王五").setAge(26).setBir(new Date());
userDAO.insert(user);
}
3、修改方法
@Test
public void testUpdateById(){
User user = userDAO.selectById("2");
user.setName("二麻");
userDAO.updateById(user);
}
@Test
public void testUpdate(){
User user = new User();
user.setName("殿下");
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("age", 22);
userDAO.update(user, queryWrapper);
}
4、删除方法
@Test
public void testDeleteById(){
userDAO.deleteById("2");
}
@Test
public void testDelete(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.ge("age", 26);
userDAO.delete(wrapper);
}
五、多数据源配置实现读写分离
1、引入dynamic-datasource-spring-boot-starter依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2、配置数据源
spring:
datasource:
dynamic:
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/mybatis-plus?characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
slave_1:
url: jdbc:mysql://localhost:3306/mybatis-plus1?characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
slave_2:
url: jdbc:mysql://localhost:3306/mybatis-plus2?characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
3、使用 @DS 切换数据源
public interface UserService {
List<User> findAllUser();
void saveUser(User user);
}
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
@DS("slave_1")
public List<User> findAllUser() {
return userDAO.selectList(null);
}
@Override
public void saveUser(User user) {
userDAO.insert(user);
}
}
4、测试代码
@SpringBootTest
public class TestUserService {
@Autowired
private UserService userService;
@Test
public void testFindAll(){
List<User> users = userService.findAllUser();
users.forEach(user -> System.out.println("user=" + user));
}
@Test
public void testSave(){
User user = new User();
user.setName("哈哈").setAge(55).setBir(new Date());
userService.saveUser(user);
}
}
|