springboot中使用mybatis-plus

欢迎大家一起学习mybatis-plus框架

一起学习,一起努力

目录

一、springboot中使用mybatis-plus

1. 在Maven添加MyBatis Plus依赖。

2. 配置数据源

3. 创建实体类

4. 创建Mapper接口

5. 进行查询操作

二、Mybatis-plus中的BaseMappe常用CRUD封装方法

插入方法

更新方法

删除方法

查询方法


一、springboot中使用mybatis-plus

1. 在Maven添加MyBatis Plus依赖。

对于Maven用户,在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>{你的版本}</version>
</dependency>

2. 配置数据源

application.properties(或application.yml文件中配置数据源信息:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

3. 创建实体类

创建一个Java类表示数据库表中的一行记录,并使用@TableName注解指定与之关联的表名。例如:

@Data
@TableName("user")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
}

使用了Lombok来简化代码,同时使用了MyBatis Plus提供的@TableId注解来标识主键,并指定主键生成策略为自增。

4. 创建Mapper接口

创建一个Java接口,继承BaseMapper,并指定泛型类型为你的实体类。例如:

public interface UserMapper extends BaseMapper<User> {
}

使用了MyBatis Plus提供的基类BaseMapper,它提供了许多常用的CRUD操作方法。

5. 进行查询操作

在Java代码中注入UserMapper实例,并使用它进行查询。例如:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAllUsers() {
        return userMapper.selectList(null);
    }
}

使用了MyBatis Plus提供的selectList方法来查询所有用户记录。

二、Mybatis-plus中的BaseMappe常用CRUD封装方法

插入方法

// 插入一条记录
int insert(T entity);

// 批量插入多条记录
int insertBatch(List<T> entityList);

// 插入一条记录并返回主键值
int insertAndGetId(T entity);

更新方法

// 根据主键更新记录
int updateById(T entity);

// 根据主键批量更新记录
int updateBatchById(List<T> entityList);

// 根据条件更新记录
int update(@Param("entity") T entity, @Param("updateWrapper") UpdateWrapper<T> updateWrapper);

删除方法

// 根据主键删除记录
int deleteById(Serializable id);

// 根据主键批量删除记录
int deleteBatchIds(Collection<? extends Serializable> idList);

// 根据条件删除记录
int delete(@Param("queryWrapper") QueryWrapper<T> queryWrapper);

查询方法

// 根据主键查询记录
T selectById(Serializable id);

// 根据主键列表查询记录
List<T> selectBatchIds(Collection<? extends Serializable> idList);

// 查询所有记录
List<T> selectAll();

// 根据条件查询记录数量
int selectCount(@Param("queryWrapper") QueryWrapper<T> queryWrapper);

// 根据条件查询单条记录
T selectOne(@Param("queryWrapper") QueryWrapper<T> queryWrapper);

// 根据条件查询多条记录
List<T> selectList(@Param("queryWrapper") QueryWrapper<T> queryWrapper);

需要注意的是,这些方法都是泛型方法,其中的类型参数T表示实体类。如果你的实体类中使用了@TableId注解来标识主键,那么在调用以上CRUD操作方法时,MyBatis Plus会自动根据主键生成策略来设置主键值。

除了基本的CRUD操作方法,BaseMapper还提供了一些其它有用的方法,如批量插入或更新记录、分页查询等,下此再说

猜你喜欢

转载自blog.csdn.net/weixin_59367964/article/details/130499093