Spring boot整合MyBatis-Plus 之二:增删改查

2020-10-03 10:45|来源: 网络

基于上一篇springboot整合MyBatis-Plus之后,实现简单的增删改查


创建实体类

添加表注解TableName和主键注解TableId

import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.IdType;
import java.io.Serializable;
@TableName("t_article")
public class Article implements Serializable {
    @TableId(type = IdType.INPUT)
    private String id;
    private String title;

    ......
}


数据访问接口dao

继承BaseMapper接口,编写数据访问接口dao

public interface ArticleDao extends BaseMapper<Article> {
}


基本的增删改查示例

@Service
public class ArticleService {
    @Autowired
    private ArticleDao articleDao;
    public List<Article> findAll() {
        return articleDao.selectList(null);
    }
    public Article findById(String id) {
        return articleDao.selectById(id);
    }

    public void add(Article article) {
        articleDao.insert(article);
    }

    public void update(Article article) {
        //根据id号更新
        //方法1
        articleDao.updateById(article);
   
        //方法2
        EntityWrapper wrapper = new EntityWrapper<Article>();
        wrapper.eq("id", article.getId());
        articleDao.update(article, wrapper);
    }

    public void delete(String id) {
        articleDao.deleteById(id);
    }
}


MyBatis-Plus条件与分页查询

条件查询

使用Mybatis Plus 提供的EntityWrapper对象封装where查询条件,例如以下使用方式:

EntityWrapper wrapper = new EntityWrapper<Article>();
wrapper.eq("id", article.getId());

//动态sql,例如<if test="null != field"> and field='xxx' </if>
wrapper.eq(null != map.get(field), field, map.get(field));


分页

使用 Mybatis Plus 提供的Page对象

向Mybatis Plus中注入PaginationInterceptor插件

新建config包,创建MybatisPlusConfig对象,添加下面的代码

@Configuration
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

完整代码

public Page search(Map map, int page, int size) {
    EntityWrapper wrapper = new EntityWrapper<Article>();
    Set<String> fieldSet = map.keySet();
    for(String field : fieldSet) {
        //wrapper.eq(field, map.get(field));
        wrapper.eq(null != map.get(field), field, map.get(field));
    }

    Page page1 = new Page(page, size);
    List list = articleDao.selectPage(page1, wrapper);
    page1.setRecords(list);
    return page1;
}


本文转自网络


相关问答

更多