mybatisplus教程
时间: 2023-09-03 09:08:15 浏览: 113
Mybatis-Plus是一个Mybatis的增强工具,它在Mybatis的基础上扩展了一些功能,使得使用Mybatis更加方便、高效。它提供了很多实用的功能,比如自动填充、多租户、分页插件等。
下面是Mybatis-Plus的教程:
1. 添加Mybatis-Plus依赖
在pom.xml文件中添加Mybatis-Plus的依赖:
```
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.4.3</version>
</dependency>
```
2. 配置Mybatis-Plus
在application.yml文件中配置Mybatis-Plus:
```
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
global-config:
db-config:
id-type: auto
field-strategy: not_null
table-prefix: mp_
configuration:
map-underscore-to-camel-case: true
```
其中,mapper-locations指定了Mapper.xml文件的位置,global-config配置全局的参数,configuration配置Mybatis的参数。
3. 创建实体类
创建一个实体类,类名与数据库中表名对应,属性名与数据库中字段名对应,使用注解@TableField指定数据库中的字段名:
```
@Data
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
@TableField("name")
private String username;
private String password;
private Integer age;
private String email;
}
```
4. 创建Mapper接口
创建一个Mapper接口,继承BaseMapper接口,即可使用Mybatis-Plus提供的通用方法:
```
public interface UserMapper extends BaseMapper<User> {
}
```
5. 使用Mybatis-Plus
使用Mybatis-Plus进行数据库操作非常简单,只需要调用Mapper接口中的方法即可,如:
```
@Autowired
private UserMapper userMapper;
public void addUser(User user) {
userMapper.insert(user);
}
public User getUserById(Long id) {
return userMapper.selectById(id);
}
public List<User> getUserList() {
return userMapper.selectList(null);
}
public void updateUser(User user) {
userMapper.updateById(user);
}
public void deleteUser(Long id) {
userMapper.deleteById(id);
}
```
以上就是使用Mybatis-Plus的基本教程,如果需要更多的高级功能,可以查看Mybatis-Plus的官方文档。
阅读全文
相关推荐














