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

com.github.siwenyan.query.MyBatisQuery Maven / Gradle / Ivy

There is a newer version: 1.25
Show newest version
package com.github.siwenyan.query;

import com.github.siwenyan.common.DataTableTools;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class MyBatisQuery extends QueryBase {
    public static final Logger log = Logger.getLogger(MyBatisQuery.class.getName());

    private final SqlSessionFactory sqlSessionFactory;

    public MyBatisQuery(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public Object query(String path) {
        path = path.trim();
        List list = null;

        try (SqlSession sqlSession = this.sqlSessionFactory.openSession()) {
            String[] p = path.split("\\s+", 2);
            if (2 == p.length && "select".equals(p[0].toLowerCase())) {
                //select * from your_table where col1=val1;
                String[] lp = path.split("\\s+[lL][iI][mM][iI][tT]\\s+", 2);
                if (2 != lp.length) {
                    if (path.endsWith(";")) {
                        path = path.substring(0, path.length() - 1);
                    }
                    path += " limit 1000;";
                }
                if (!path.endsWith(";")) {
                    path += ";";
                }
                List> result = MyBatisUtils.query(sqlSession, path);
                list = new ArrayList<>(result);
            } else {
                if (2 == p.length) {
                    if (p[1].contains("=")) {
                        //Entity.selectId value
                        Map params = DataTableTools.asMap(p[1]);
                        list = sqlSession.selectList(p[0], params);
                    } else {
                        list = sqlSession.selectList(p[0], p[1]);
                    }
                } else {
                    //Entity.selectId name=value
                    list = sqlSession.selectList(path);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        if (null != list && 1 == list.size() && !(list.get(0) instanceof Map) && !(list.get(0) instanceof Collection)) {
            return list.get(0);
        } else {
            return list;
        }

    }
}