MybatisPlus01
1.MybatisPlus初体验
1.1首先要引入MybatisPlus的依赖
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.2</version></dependency>
1.2定义Mapper接口并继承BaseMapper
public interface UserMapper extends BaseMapper<User> {//在继承时,需要指定操作实体类的泛型
}
1.3直接使用
package com.itheima.mp.mapper;import com.itheima.mp.domain.po.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.time.LocalDateTime;
import java.util.List;@SpringBootTest
class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testvoid testInsert() {User user = new User();user.setId(5L);user.setUsername("Lucy");user.setPassword("123");user.setPhone("18688990011");user.setBalance(200);user.setInfo("{\"age\": 24, \"intro\": \"英文老师\", \"gender\": \"female\"}");user.setCreateTime(LocalDateTime.now());user.setUpdateTime(LocalDateTime.now());userMapper.insert(user);}@Testvoid testSelectById() {User user = userMapper.selectById(5L);System.out.println("user = " + user);}@Testvoid testQueryByIds() {List<User> users = userMapper.selectBatchIds(List.of(1L, 2L, 3L, 4L));users.forEach(System.out::println);}@Testvoid testUpdateById() {User user = new User();user.setId(5L);user.setBalance(20000);userMapper.updateById(user);}@Testvoid testDeleteUser() {userMapper.deleteById(5L);}
}
2.常用注解
MybatisPlus扫描实体类,并基于反射获取实体类信息作为数据库表信息
2.1默认约定
2.2注解使用
当你的实体,不符合默认约定时,就可以使用注解配置
- @TableName: 用来指定表名 放在实体类的上边
- @TableId: 用来指定表中的主键字段信息 放在实体类成员变量上边
- @TableField: 用来指定表中的普通字段信息 放在实体类成员变量上边