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

org.test4j.module.database.operator.InsertOp Maven / Gradle / Ivy

There is a newer version: 1.1.2
Show newest version
package org.test4j.module.database.operator;

import org.test4j.exception.Exceptions;
import org.test4j.module.database.enviroment.DBEnvironment;
import org.test4j.module.database.enviroment.DBEnvironmentFactory;
import org.test4j.module.database.enviroment.TableMeta;
import org.test4j.tools.datagen.IDataMap;

import java.io.InputStream;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.Map;

/**
 * 插入数据操作
 *
 * @author wudarui
 */
@SuppressWarnings({"unchecked", "rawtypes", "unused"})
public class InsertOp implements IInsertOp {
    private String table;

    private final DBEnvironment env;

    private TableMeta tableMeta;

    public InsertOp() {
        this(DBEnvironmentFactory.getDefaultDBEnvironment());
    }

    public InsertOp(DBEnvironment environment) {
        this.env = environment;
    }

    public static void insertNoException(DBEnvironment env, String table, IDataMap data) {
        try {
            InsertOp op = new InsertOp(env);
            op.insert(table, data);
        } catch (Exception e) {
            throw Exceptions.getUndeclaredThrowableExceptionCaused(e);
        }
    }

    /**
     * 往数据库中插入数据
     *
     * @param table 表
     * @param data  要插入的数据
     */
    @Override
    public void insert(String table, IDataMap data) {
        this.table = table;
        this.tableMeta = env.getTableMetaData(table);
        tableMeta.fillData(data, env);
        List> datas = data.rows();
        for (Map map : datas) {
            env.execute(connection -> {
                PreparedStatement st = connection.prepareStatement(getInsertCommandText(map));
                return this.setParametersByMap(st, map);
            }, PreparedStatement::execute);
        }
    }

    private PreparedStatement setParametersByMap(PreparedStatement statement, Map map) {
        int index = 1;
        for (String key : map.keySet()) {
            try {
                Object value = getValueByColumn(key, map);
                if (value instanceof InputStream) {
                    InputStream is = (InputStream) value;
                    statement.setBinaryStream(index, is, is.available());
                } else {
                    Object sqlValue = env.convertToSqlValue(value);
                    statement.setObject(index, sqlValue);
                }
                index++;
            } catch (Throwable e) {
                throw new RuntimeException("set column[" + key + "] value error:" + e.getMessage(), e);
            }
        }
        return statement;
    }

    private Object getValueByColumn(String column, Map map) {
        Object value = map.get(column);
        if (!(value instanceof String)) {
            return value;
        }
        String javaType = this.tableMeta.getColumnType(column);
        if (String.class.getName().equals(javaType)) {
            value = this.tableMeta.truncateString(column, (String) value);
        } else {
            value = env.toObjectValue((String) value, javaType);
        }
        return value;
    }

    /**
     * 构造map的insert sql语句
     *
     * @param map 要插入的数据
     * @return sql
     */
    private String getInsertCommandText(Map map) {
        StringBuilder text = new StringBuilder();
        StringBuilder values = new StringBuilder();

        text.append("insert into ").append(this.env.wrapper(table)).append("(");
        boolean isFirst = true;
        for (String key : map.keySet()) {
            if (isFirst) {
                isFirst = false;
            } else {
                text.append(",");
                values.append(",");
            }
            text.append(this.env.wrapper(key));
            values.append("?");
        }

        text.append(") values(").append(values).append(")");
        return text.toString();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy