hutool.db.sql 工具类与Springboot、MyBatis整合

@Component
@Slf4j
public class HutoolSqlUtil {
    @Autowired
    DynamicDataSourceProperties dynamicDataSourceProperties;
    private Db db;

    private DruidDataSource createDataSource() {
        Map<String, DataSourceProperty> dataSourceMap = dynamicDataSourceProperties.getDatasource();
        if (null == dataSourceMap) {
            throw exception(DATA_SOURCE_CONFIG_NOT_EXISTS);
        }
        DataSourceProperty dataSourceProperty = MapUtil.get(dataSourceMap, "master", DataSourceProperty.class);
        if (null == dataSourceProperty) {
            throw exception(DATA_SOURCE_CONFIG_NOT_EXISTS);
        }
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(dataSourceProperty.getUrl());
        ds.setUsername(dataSourceProperty.getUsername());
        ds.setPassword(dataSourceProperty.getPassword());
        return ds;
    }

    public Db getDb() {
        if (null == db) {
            db = Db.use(createDataSource());
        }
        return db;
    }

    public PageResult<Entity> page(InstancePageReqVO pageReqVO) {
        try {
            SqlBuilder sqlBuilder = SqlBuilder.create().select("*")
                    .from(pageReqVO.getFormCode());
            List<Condition> conditionList = new ArrayList<>();
            if (null != pageReqVO.getCreateTime()) {
                Condition createTimeCondition = new Condition("create_time", "BETWEEN", pageReqVO.getCreateTime()[0]);
                createTimeCondition.setSecondValue(pageReqVO.getCreateTime()[1]);
                conditionList.add(createTimeCondition);
            }
            if (null != pageReqVO.getSearchFieldVos()) {
                pageReqVO.getSearchFieldVos().forEach(search -> {
                    Condition condition = new Condition(search.getFiled(), search.getValue(), Condition.LikeType.Contains);
                    conditionList.add(condition);
                });
            }
            if (!conditionList.isEmpty()) {
                Condition[] conditions = conditionList.toArray(new Condition[0]);
                sqlBuilder.where(conditions);
            }

            Page page = new Page(pageReqVO.getPageNo() - 1, pageReqVO.getPageSize());
            long totalCount = getDb().count(sqlBuilder);
            PageResult<Entity> result = getDb().page(sqlBuilder, page, PageResultHandler.create(new PageResult<>()));
            PageResult<Entity> pageResult = PageResult<>();
            pageResult.setList(result);
            pageResult.setTotal(totalCount);
            return pageResult;
        } catch (Exception exception) {
            log.error("hutool 分页查询失败:" + exception);
            throw exception(HUTOOL_PAGE_ERROR);
        }

    }

    public List<Entity> findAll(String table) {
        try {
            Entity getWhere = Entity.create(table).set("id", new long[]{1, 2, 3});
            return getDb().findAll(getWhere);
        } catch (Exception exception) {
            log.error("hutool 查询列表失败:" + exception);
            throw exception(HUTOOL_FIND_ALL_ERROR);
        }
    }

    public Entity get(String table, Long id) {
        try {
            Entity getWhere = Entity.create(table).set("id", id);
            return getDb().get(getWhere);
        } catch (Exception exception) {
            log.error("hutool 详情查询失败:" + exception);
            throw exception(HUTOOL_GET_ERROR);
        }
    }

    public void delete(String table, Long id) {
        try {
            Entity getWhere = Entity.create(table).set("id", id);
            getDb().del(getWhere);
        } catch (Exception exception) {
            log.error("hutool 删除失败:" + exception);
            throw exception(HUTOOL_DELETE_ERROR);
        }
    }


    public void update(String table, Long id, Map<String, Object> data) {
        try {

            Entity entity = Entity.create(table);
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                if (entry.getValue() instanceof ArrayList) {
                    entity.set(entry.getKey(), JSONObject.toJSONString(entry.getValue()));
                } else {
                    entity.set(entry.getKey(), entry.getValue());
                }
            }
            Entity updateWhere = Entity.create(table).set("id", id);
            getDb().update(entity, updateWhere);
        } catch (Exception exception) {
            log.error("hutool 更新失败:" + exception);
            throw exception(HUTOOL_UPDATE_ERROR);
        }
    }

    public Long insert(String table, Map<String, Object> data) {
        try {

            Entity entity = Entity.create(table);
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                if (entry.getValue() instanceof ArrayList) {
                    entity.set(entry.getKey(), JSONObject.toJSONString(entry.getValue()));
                } else {
                    entity.set(entry.getKey(), entry.getValue());
                }

            }
            return getDb().insertForGeneratedKey(entity);
        } catch (Exception exception) {
            log.error("hutool 插入失败:" + exception);
            throw exception(HUTOOL_INSERT_ERROR);
        }
    }
}

如果不需要整合

在resource下增加配置文件db.setting

#------------------------------------------------------------------------------------------
## 基本配置信息
# JDBC URL,根据不同的数据库,使用相应的JDBC连接字符串
url = 
# 用户名,此处也可以使用 user 代替
username = root
# 密码,此处也可以使用 pass 代替
password = root
# JDBC驱动名,可选(Hutool会自动识别)
driver = com.mysql.jdbc.Driver

## 可选配置
# 是否在日志中显示执行的SQL
showSql = true
# 是否格式化显示的SQL
formatSql = false
# 是否显示SQL参数
showParams = true
# 打印SQL的日志等级,默认debug
sqlLevel = debug
#------------------------------------------------------------------------------------------


修改代码getDb()方法

    public Db getDb() {
        if (null == db) {
            db = Db.use();
        }
        return db;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值