MyBatis-Plus(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。今天我们主要通过一个简单的案例来体会MyBatis-Plus功能的强大之处。
话不多说,直接进入正题
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
具体步骤可以参考spring boot工程的创建
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
#配置dataSource
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
username: root
password: root
#配置日志,方便查看sql语句
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
@Component
public interface UserMapper extends BaseMapper<User> {
//这里不需要写任何代码
//MyBatis-Plus已经给我们准备好了,直接拿来用即可
}
@SpringBootTest
@MapperScan("com.example.dao") //扫描数据层接口所在的包
class MybatisPlusApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testInsert(){
User user = new User();
user.setName("aaa");
user.setAge(3);
user.setEmail("[email protected]");
int insert = userMapper.insert(user);
System.out.println(insert);
}
}
@Test
public void testUpdate(){
User user = new User();
user.setId(6L);
user.setName("dada");
user.setEmail("[email protected]");
int i = userMapper.updateById(user);
System.out.println(i);
}
这里我们删除 id 为 6 的用户
// 测试通过id单个删除
@Test
public void testDeleteById(){
userMapper.deleteById(1L);
}
删除之前我们先多插入几条数据,方便测试
// 测试通过id批量删除
@Test
public void testDeleteBatchIds(){
userMapper.deleteBatchIds(Arrays.asList(8L,9L,10L));
}
// 测试通过map批量删除
@Test
public void testDeleteByMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("age","18");
userMapper.deleteByMap(map);
}
// 测试通过id查询
@Test
public void testSelectById(){
User user = userMapper.selectById(2);
System.out.println(user);
}
@Test
public void selectList() {
List<User> list = userMapper.selectList(null);
list.forEach(System.out::println);
}