1.创建项目,导入依赖
<!--mybatisplus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
2. 创建实体类
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date modifyTime;
}
3.创建mapper接口
创建的mapper接口需要继承BaseMapper并设置类型为实体类型,这样就能根据实体类名与数据库表绑定了。
@Repository
public interface UserMapper extends BaseMapper<User> {
}
4.包扫描
在springboot主启动类上添加mapperScan("")注解将mapper加入到spring容器中。
@SpringBootApplication
@MapperScan("com.example.mybatisplusexample.mapper")
public class MybatisplusExampleApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusExampleApplication.class, args);
}
}
5.测试
@SpringBootTest
class MybatisplusExampleApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
//插入:主键非空会根据雪花算法生成一个唯一的id
User user=new User();
user.setAge(21);
user.setEmail("233");
user.setName("zhangsan");
userMapper.insert(user);
}
}