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, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
com.baomidou
mybatis-plus-boot-starter
3.5.2
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
#配置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 {
//这里不需要写任何代码
//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("88888888@qq.com");
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("22222222@qq.com");
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));
}
我们再添加一条数据,删除数据表中年龄等于 18 岁的用户
// 测试通过map批量删除
@Test
public void testDeleteByMap(){
HashMap 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 list = userMapper.selectList(null);
list.forEach(System.out::println);
}
至此,MyBatis-Plus实现的CRUD就告一段落了,有没有觉得特别爽!!!
先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦