All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.fhs.pagex.service.PageXDBService Maven / Gradle / Ivy

The newest version!
package com.fhs.pagex.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fhs.pagex.dto.PagexAddDTO;
import com.fhs.redis.service.RedisCacheService;
import com.mybatis.jpa.cache.JpaTools;
import com.fhs.common.utils.*;
import com.fhs.core.base.bean.SuperBean;
import com.fhs.core.exception.BusinessException;
import com.fhs.core.trans.TransService;
import com.fhs.pagex.bean.DefaultPageXBean;
import com.mybatis.jpa.common.ColumnNameUtil;
import org.apache.commons.collections.map.HashedMap;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * pagex dbservice
 * 1 根据配置文件拼接sql
 * 2 根据namespace 执行sql返回结果
 *
 * @ProjectName: framework_v2_idea2
 * @Package: com.fhs.pagex.service
 * @ClassName: PageXDBService
 * @Author: JackWang
 * @CreateDate: 2018/12/3 0003 20:01
 * @UpdateUser: JackWang
 * @UpdateDate: 2018/12/3 0003 20:01
 * @Version: 1.0
 */
@Service
public class PageXDBService {


    private static final Logger LOG = Logger.getLogger(PageXDBService.class);

    @Autowired
    private SqlSessionTemplate sqlsession;


    @Autowired
    private TransService transService;

    @Autowired
    private RedisCacheService redisCacheService;

    private static final String DO_CACHE_KEY = "docache:";


    /**
     * 需要翻译的namespace集合
     */
    private Set needTransNamespaceSet = Collections.synchronizedSet(new HashSet<>());

    /**
     * key namespace value 对应namespace的PO class
     */
    private Map namespaceClassMap = new ConcurrentHashMap<>();


    /**
     * 插入一条数据到db
     *
     * @param paramMap  参数
     * @param namespace namespace
     * @return
     */
    public int insert(EMap paramMap, String namespace) {
        insertAndUpdateX(paramMap, namespace, true);
        return sqlsession.insert(getSqlNamespace() + namespace + "_insertPageX", paramMap);
    }

    /**
     * 处理一对多
     *
     * @param paramMap  参数
     * @param namespace namespace
     */
    private void insertAndUpdateX(EMap paramMap, String namespace, boolean isAdd) {
        PagexAddDTO addDTO = PagexDataService.SIGNEL.getPagexAddDTOFromCache(namespace);
        Map modelConfig = addDTO.getModelConfig();


        //是否存在一对多
        if (ConverterUtils.toBoolean(addDTO.getModelConfig().get("isOne2X"))) {
            String createUser = isAdd ? paramMap.getStr("createUser") : paramMap.getStr("updateUser");
            String groupCode = paramMap.getStr("groupCode");
            String pkey = isAdd ? paramMap.getStr("pkey") : paramMap.getStr(modelConfig.get("pkey"));
            List namespaces = new ArrayList<>();
            List> fields = addDTO.getFormFieldSett();
            //把所有的namespace拿到
            for (Map field : fields) {
                if ("one2x".equals(field.get("type"))) {
                    namespaces.add(ConverterUtils.toString(field.get("namespace")));
                }
            }
            // ConverterUtils.toString(modelConfig.get("xNamespaces")).split(",");
            JSONArray tempJsonArray = null;
            Map deleteFKeyParam = new HashMap<>();
            deleteFKeyParam.put("fkey", pkey);
            //遍历一对多的数据然后插入
            for (String xNamespace : namespaces) {

                sqlsession.delete(getSqlNamespace() + xNamespace + "_delFkeyPageX", deleteFKeyParam);
                //取出fkey的列名字
                String fkeyField = ColumnNameUtil.underlineToCamel(ConverterUtils.toString(PagexDataService.SIGNEL.getPagexAddDTOFromCache(xNamespace).getModelConfig().get("fkey")));
                String pkeyField = ConverterUtils.toString(PagexDataService.SIGNEL.getPagexAddDTOFromCache(xNamespace).getModelConfig().get("pkey"));
                tempJsonArray = JSON.parseArray(ConverterUtils.toString(paramMap.get(xNamespace)));
                for (int i = 0; i < tempJsonArray.size(); i++) {
                    JSONObject extendsChild = tempJsonArray.getJSONObject(i);
                    //没有id就生成一个
                    if (!extendsChild.containsKey("pkey")) {
                        extendsChild.put("pkey", StringUtil.getUUID());
                    }
                    redisCacheService.remove(DO_CACHE_KEY + xNamespace + ":" + extendsChild.get("pkey"));
                    extendsChild.put(fkeyField, pkey);
                    extendsChild.put("updateUser", createUser);
                    extendsChild.put("createUser", createUser);
                    extendsChild.put("groupCode", groupCode);
                    sqlsession.insert(getSqlNamespace() + xNamespace + "_insertPageX", extendsChild);
                }
            }
        }
    }

    /**
     * 获取数据带分页
     *
     * @param param     参数
     * @param namespace namespace
     * @return json
     */
    public String findListPage(Map param, String namespace) {
        List> rows = sqlsession.selectList(getSqlNamespace() + namespace + "_findPageX", param);
        //如果不包含的话就直接转换为json
        if (!needTransNamespaceSet.contains(namespace)) {
            return JsonUtils.list2json(rows);
        }
        final Class clazz = namespaceClassMap.get(namespace);
        final List> superBeans = new ArrayList<>();
        // List map 转List SuperBean
        rows.forEach(row -> {
            try {
                Object tempObj = clazz.newInstance();
                SuperBean tempSuperBenn = (SuperBean) tempObj;
                for (String key : row.keySet()) {
                    ReflectUtils.setValue(tempObj, key, ConverterUtils.toString(row.get(key)));
                }
                superBeans.add(tempSuperBenn);
            } catch (InstantiationException e) {
                LOG.error(this, e);
                throw new BusinessException("findListPager反射错误");
            } catch (IllegalAccessException e) {
                LOG.error(this, e);
                throw new BusinessException("findListPager反射错误参数错误");
            }
        });
        transService.transMore(superBeans);
        return JsonUtils.list2json(superBeans);
    }

    /**
     * 查询总数
     *
     * @param param     参数
     * @param namespace namespace
     * @return 总数
     */
    public Integer findPageCount(Map param, String namespace) {
        Map countRow = sqlsession.selectOne(getSqlNamespace() + namespace + "_findPageCountPageX", param);
        return ConverterUtils.toInt(countRow.get("countNum"));
    }

    /**
     * 获取bena的json
     *
     * @param param     过滤参数
     * @param namespace namespace
     * @return bean的json
     */
    public String findBean(Map param, String namespace) {
        return JsonUtils.bean2json(sqlsession.selectOne(getSqlNamespace() + namespace + "_findBeanPageX", param));
    }

    /**
     * 获取bena的json
     *
     * @param paramMap  过滤参数
     * @param namespace namespace
     * @return 更新了几行默认是1
     */
    public int update(EMap paramMap, String namespace) {
        insertAndUpdateX(paramMap, namespace, false);
        redisCacheService.remove(DO_CACHE_KEY + namespace + ":" + paramMap.get("id"));
        return sqlsession.update(getSqlNamespace() + namespace + "_updatePageX", paramMap);
    }

    /**
     * 获取bena的json
     *
     * @param pkey      主键
     * @param namespace namespace
     * @return 删除了几行 理论来说是1
     */
    public int del(String pkey, String namespace) {
        redisCacheService.remove(DO_CACHE_KEY + namespace + ":" + pkey);
        return sqlsession.delete(getSqlNamespace() + namespace + "_delPageX", pkey);
    }

    /**
     * 获取mybatis 命名空间
     *
     * @return
     */
    private String getSqlNamespace() {
        String sqlNameSpace = JpaTools.statementAdapterMap.get(DefaultPageXBean.class.getName()).getNameSpace();
        return sqlNameSpace + ".";
    }


    public Map getNamespaceClassMap() {
        return this.namespaceClassMap;
    }

    public Set getNeedTransNamespaceSet() {
        return needTransNamespaceSet;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy