基于mybatis的动态表数据增删改查方法实现

Posted 洛阳泰山

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于mybatis的动态表数据增删改查方法实现相关的知识,希望对你有一定的参考价值。

实体类


import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Data
public class DynamicEntity {

    /** 主键 */
    @TableId(value = "id",type= IdType.ASSIGN_ID)
    private Long id;

    private String tableName;

    private Map<String,Object> params;

    SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void setParams(Map<String, Object> params) {
        params.forEach((k,v)->{
            if(v instanceof String){
                try {
                  Date date= dateFormat.parse(v.toString());
                  params.put(k,date);
                } catch (ParseException e) {
                   params.put(k,v);
                }
            }
        });
        params.put("id",id);
        params.put("create_time",new Date());
        this.params = params;
    }

}

mapper类


import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Mapper;
import org.springblade.gis.modules.dynamic.entity.DynamicEntity;
import org.springblade.gis.modules.dynamic.wrapper.DynamicWrapper;

import java.util.List;
import java.util.Map;

@Mapper
public interface DynamicMapper  {

    Long insert(DynamicEntity entity);

    int updateById(DynamicEntity entity);

    @MapKey("id")
    List<Map<String,Object>> selectById(String tableName, Long id);

    @MapKey("id")
    List<Map<String,Object>> selectList(DynamicWrapper entity);

    int deleteById(String tableName, Long id);

    Long selectCount(DynamicWrapper entity);

}

service类


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springblade.gis.modules.dynamic.mapper.DynamicMapper;
import org.springblade.gis.modules.dynamic.entity.DynamicEntity;
import org.springblade.gis.modules.dynamic.wrapper.DynamicWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class DynamicService {

    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    @Resource
    private DynamicMapper dynamicMapper;

    public Long save(DynamicEntity entity) {
        return dynamicMapper.insert(entity);
    }

    public Boolean saveBatch(List<DynamicEntity> list) {
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        dynamicMapper = session.getMapper(DynamicMapper.class);
        try {
            if (CollectionUtils.isNotEmpty(list)) {
                int num = list.size();
                for (int i = 0; i < num; i++) {
                    dynamicMapper.insert(list.get(i));
                    if ((i > 0 && i % 1000 == 0) || i == num - 1) {
                        session.commit();
                        session.clearCache();
                    }
                }
            }
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
        return true;
    }

    public int updateById(DynamicEntity entity){
        return dynamicMapper.updateById(entity);
    }

    public List<Map<String, Object>> getById(String tableName,Long id){
        return dynamicMapper.selectById(tableName,id);
    }

    public List<Map<String, Object>> list(DynamicWrapper wrapper){
        if(StringUtils.isBlank(wrapper.getColumns())){
            wrapper.setColumns("*");
        }
        return dynamicMapper.selectList(wrapper);
    }

    public Long count(DynamicWrapper entity){
        return dynamicMapper.selectCount(entity);
    }

    public Boolean removeByIds(String tableName,List<Long> ids){
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        dynamicMapper = session.getMapper(DynamicMapper.class);
        try {
            if (CollectionUtils.isNotEmpty(ids)) {
                int num = ids.size();
                for (int i = 0; i < num; i++) {
                    dynamicMapper.deleteById(tableName,ids.get(i));
                    if ((i > 0 && i % 1000 == 0) || i == num - 1) {
                        session.commit();
                        session.clearCache();
                    }
                }
            }
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
        return true;
    }


}

wrapper类


import lombok.Data;

import java.util.Map;

@Data
public class DynamicWrapper {

    private String tableName;

    private String columns;

    private Map<String,Object> params;
}

controller类


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.secure.annotation.NoToken;
import org.springblade.core.tool.api.R;
import org.springblade.gis.modules.dynamic.entity.DynamicEntity;
import org.springblade.gis.modules.dynamic.service.DynamicService;
import org.springblade.gis.modules.dynamic.wrapper.DynamicWrapper;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@NoToken
@RestController
@AllArgsConstructor
@RequestMapping("dynamic")
@Api(value = "数据库表数据", tags = "数据库表数据")
public class DynamicController {

    private final DynamicService dynamicService;

    @ApiOperation(value = "分页 @author Tarzan Liu")
    @GetMapping("page/{tableName}")
    public R<IPage<Map<String,Object>>> pageList(@PathVariable("tableName") String tableName, @RequestParam Map<String,Object> params) {
        IPage page=new Page();
        if(params.get("current")!=null){
            page.setCurrent((Long) params.get("current"));
        }else{
            page.setCurrent(1);
        }
        if(params.get("size")!=null){
            page.setSize((Long) params.get("size"));
        }else{
            page.setSize(1000);
        }
        DynamicWrapper wrapper=new DynamicWrapper();
        wrapper.setTableName(tableName);
        wrapper.setParams(params);
        page.setTotal(dynamicService.count(wrapper));
        Long pages;
        if(page.getTotal()%page.getSize()==0){
            pages=page.getTotal()/page.getSize();
        }else{
            pages=page.getTotal()/page.getSize()+1;
        }
        page.setPages(pages);
        page.setRecords(dynamicService.list(wrapper));
        return R.data(page);
    }


    @ApiOperation(value = "批量添加 @author Tarzan Liu")
    @PostMapping("saveBatch/{tableName}")
    public R<List<Long>> saveBatch(@PathVariable("tableName") String tableName,@RequestBody List<Map<String,Object>> maps) {
        List<DynamicEntity> list=maps.stream().map(e->{
            DynamicEntity entity=new DynamicEntity();
            entity.setId(IdWorker.getId(DynamicEntity.class));
            entity.setParams(e);
            entity.setTableName(tableName);
            return entity;
        }).collect(Collectors.toList());
        dynamicService.saveBatch(list);
        return  R.data(list.stream().map(DynamicEntity::getId).collect(Collectors.toList()));
    }

    @ApiOperation(value = "详情 @author Tarzan Liu")
    @PostMapping("get/{tableName}/{id}")
    public R<List<Map<String, Object>>> get(@PathVariable("tableName") String tableName,@PathVariable("id") Long id) {
        return R.data(dynamicService.getById(tableName,id));
    }

    @ApiOperation(value = "修改 @author Tarzan Liu")
    @PostMapping("update/{tableName}")
    public R<Boolean> update(@PathVariable("tableName") String tableName, @RequestBody Map<String,Object> map) {
        DynamicEntity entity=new DynamicEntity();
        entity.setParams(map);
        entity.setTableName(tableName);
        entity.setId((Long) map.get("id"));
        int flag= dynamicService.updateById(entity);
        return R.status(flag>0?true:false);
    }

    @ApiOperation(value = "删除 @author Tarzan Liu")
    @PostMapping("delete/{tableName}")
    public R<Boolean> delete(@PathVariable("tableName")String tableName,@RequestBody List<Long> ids) {
        return R.status(dynamicService.removeByIds(tableName,ids));
    }
}

以上是关于基于mybatis的动态表数据增删改查方法实现的主要内容,如果未能解决你的问题,请参考以下文章

mybatis实战教程(mybatis in action)之三:实现数据的增删改查

Java Web009 -- MyBatis(入门 & 增删改查 & 动态SQL)

Mybatis实现增删改查

基于JdbcTemplate 的动态数据,增删改查功能实现

Mybatis通用Mapper

Mybatis通用Mapper