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

com.cherokeesoft.db.utils.VelocityJdbcTemplate Maven / Gradle / Ivy

There is a newer version: 1.8.29
Show newest version
package com.cherokeesoft.db.utils;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.CharEncoding;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.simpleflatmapper.jdbc.spring.ResultSetExtractorImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.*;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.util.Assert;

import java.io.StringWriter;
import java.sql.*;
import java.util.*;

public class VelocityJdbcTemplate {
    private static final Logger LOG = LoggerFactory.getLogger(VelocityJdbcTemplate.class);
    private static final String SUB_DIR = "/sql";

    private NamedParameterJdbcTemplate templateJdbcTemplate;

    public VelocityJdbcTemplate(NamedParameterJdbcTemplate templateJdbcTemplate) {
        this.templateJdbcTemplate = templateJdbcTemplate;
        init();
    }

    public void init() {
        Properties p = new Properties();
        p.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        p.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        Velocity.init( p );
    }

    public  T insert(String templateName, O t, ParameterizedPreparedStatementSetter setter, Class keyType) throws SQLException {
        List result = batchInsert(templateName, Arrays.asList(t), setter, keyType);
        return result.get(0);
    }


    public  T insert(String templateName, ParameterizedPreparedStatementSetter setter, Class keyType) throws SQLException {
        List result = batchInsert(templateName, Arrays.asList(1), setter, keyType);
        return result.get(0);
    }

    public Integer insert(String templateName, SqlParameterSource sqlParameterSource) {
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        templateJdbcTemplate.update(merge(templateName, sqlParameterSource).getSql(), sqlParameterSource, keyHolder, new String[] {"id"});
        return keyHolder.getKey().intValue();
    }

    public Number insert(String templateName, Map param) {
        MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource();
        sqlParameterSource.addValues(param);
        return insert(templateName, sqlParameterSource);
    }

    public  T query(String templateName, SqlParameterSource sqlParameterSource, ResultSetExtractor mapper) {
        return templateJdbcTemplate.query(merge(templateName, sqlParameterSource).getSql(), sqlParameterSource, mapper);
    }

    public  List query(String templateName, Map params, ResultSetExtractorImpl resultSetExtractor) {
        MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
        mapSqlParameterSource.addValues(params);
        return query(templateName, mapSqlParameterSource, resultSetExtractor);
    }

    public  List query(String templateName, RowMapper mapper) {
        return query(templateName, new HashMap<>(), mapper);
    }

    public  List query(String templateName, Map params, Class claszz) {
        return templateJdbcTemplate.queryForList(merge(templateName, params).getSql(), params, claszz);
    }

    public  List query(String templateName, Map params, RowMapper mapper) {
        MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
        mapSqlParameterSource.addValues(params);
        return query(templateName, mapSqlParameterSource, mapper);
    }

    public  List query(String templateName, SqlParameterSource sqlParameterSource, RowMapper mapper) {
        return templateJdbcTemplate.query(merge(templateName, sqlParameterSource).getSql(), sqlParameterSource, mapper);
    }

    public  T queryForObject(String template, SqlParameterSource sqlParameterSource, RowMapper mapper) {
        return templateJdbcTemplate.queryForObject(merge(template, sqlParameterSource).getSql(), sqlParameterSource, mapper);
    }

    public  List batchInsert(String template, Collection data, ParameterizedPreparedStatementSetter parameterizedPreparedStatementSetter, Class keyClass) throws SQLException {
        List result = templateJdbcTemplate.getJdbcTemplate().execute(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                return connection.prepareStatement(merge(template).getSql(), Statement.RETURN_GENERATED_KEYS);
            }
        }, preparedStatement -> {
            for (T o : data) {
                parameterizedPreparedStatementSetter.setValues(preparedStatement, o);
                preparedStatement.addBatch();
            }
            preparedStatement.executeBatch();
            ResultSet resultSet = preparedStatement.getGeneratedKeys();
            List ids = new ArrayList<>();
            while (resultSet.next()) {
                ids.add(resultSet.getObject(1, keyClass));
            }
            return ids;
        });
        return result;
    }

    public  Integer batchDelete(String template, Collection data, ParameterizedPreparedStatementSetter parameterizedPreparedStatementSetter) throws SQLException {
        return templateJdbcTemplate.getJdbcTemplate().execute((PreparedStatementCreator) connection -> connection.prepareStatement(merge(template).getSql()), preparedStatement -> {
            for (T o : data) {
                parameterizedPreparedStatementSetter.setValues(preparedStatement, o);
                preparedStatement.addBatch();
            }
            preparedStatement.executeBatch();
            return 1;
        });
    }

    public  List batchInsert(String template, Collection data, ParameterizedPreparedStatementSetter parameterizedPreparedStatementSetter) throws SQLException {
        return batchInsert(template, data, parameterizedPreparedStatementSetter, Integer.class);
    }

    public void batchInsert(String template, SqlParameterSource[] params) throws SQLException {
        Assert.notEmpty(params, String.format("Params must not be empty"));
        templateJdbcTemplate.batchUpdate(merge(template, params[0]).getSql(), params);
    }

    public int[] batchUpdate(String template, SqlParameterSource[] params) throws SQLException {
        Assert.notEmpty(params, String.format("Params must not be empty"));
        return templateJdbcTemplate.batchUpdate(merge(template, params[0]).getSql(), params);
    }

    public  List queryForList(String templateName, Class aClass) {
        return templateJdbcTemplate.queryForList(merge(templateName).getSql(), new HashedMap(),aClass);
    }

    public int update(String templateName) {
        return templateJdbcTemplate.update(merge(templateName).getSql(), new HashMap<>());
    }

    public int update(String templateName, Map params) {
        MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource();
        sqlParameterSource.addValues(params);
        return templateJdbcTemplate.update(merge(templateName, sqlParameterSource).getSql(), sqlParameterSource);
    }

    public int update(String templateName, SqlParameterSource sqlParameterSource) {
        return templateJdbcTemplate.update(merge(templateName, sqlParameterSource).getSql(), sqlParameterSource);
    }

    public int delete(String templateName) {
        return delete(templateName, new HashMap<>());
    }

    public int delete(String templateName, Map params) {
        MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource();
        sqlParameterSource.addValues(params);
        return delete(templateName, sqlParameterSource);
    }

    public int delete(String templateName, SqlParameterSource sqlParameterSource) {
        return templateJdbcTemplate.update(merge(templateName, sqlParameterSource).getSql(), sqlParameterSource);
    }

    public  int[] update(String template, Collection data, ParameterizedPreparedStatementSetter statementSetter) {
        return templateJdbcTemplate.getJdbcTemplate().execute(merge(template).getSql(), new PreparedStatementCallback() {
            @Override
            public int[] doInPreparedStatement(PreparedStatement preparedStatement) throws SQLException, DataAccessException {
                for (T o : data) {
                    statementSetter.setValues(preparedStatement, o);
                    preparedStatement.addBatch();
                }
                return preparedStatement.executeBatch();
            }
        });
    }

    public PreparedToolContext merge(String templateName) {
        return merge(templateName,new HashedMap());
    }

    public PreparedToolContext merge(String templateName, SqlParameterSource sqlParameterSource) {
        Map params = Arrays.stream(sqlParameterSource.getParameterNames()).collect(HashMap::new, (m,v)->m.put(v, sqlParameterSource.getValue(v)), HashMap::putAll);
        return merge(templateName ,params);
    }

    public PreparedToolContext merge(String templateName, Map params) {
        if(LOG.isDebugEnabled()) {
            if(MapUtils.isNotEmpty(params)) {
                Set objects = params.keySet();
                for(Object key: objects) {
                    LOG.debug(String.format("key: %s value: %s \n", key, params.get(key)));
                }
            }
        }
        PreparedToolContext preparedToolContext = new PreparedToolContext(templateName, params);
        LOG.debug(preparedToolContext.getSql());
        return preparedToolContext;
    }

    private class PreparedToolContext {
        private String sql;

        public PreparedToolContext(String templateName, Map params) {
            VelocityContext context = new VelocityContext();
            if(params != null) {
                params.keySet().stream().forEach(k -> {
                    context.put((String) k, params.get(k));
                });
            }
            StringWriter writer = new StringWriter();
            Velocity.mergeTemplate(new StringBuilder(SUB_DIR).append("/").append(templateName).toString(), CharEncoding.UTF_8, context, writer);
            writer.flush();
            sql = writer.toString();
        }

        public String getSql() {
            return sql;
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy