com.kukababy.plus.dao.InsertImpl Maven / Gradle / Ivy
The newest version!
/**
*
*/
package com.kukababy.plus.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.script.ScriptEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import com.kukababy.plus.exception.PlusRuntimeException;
import com.kukababy.plus.pojo.SqlPo;
import com.kukababy.plus.pojo.SqlCfg;
import com.kukababy.plus.pojo.SqlVal;
import com.kukababy.plus.utils.Constant;
import com.kukababy.plus.utils.SqlUtil;
/**
*
* 描述:
*
*
* @author [email protected]
* @date 2019年3月5日 下午10:52:20
*/
public class InsertImpl extends BasePlus implements InsertFace {
private static final Logger log = LoggerFactory.getLogger(InsertImpl.class);
/**
* @param injectParam
*/
public InsertImpl(SqlCfg sqlCfg, ScriptEngine engine) {
super(sqlCfg,engine);
// TODO Auto-generated constructor stub
}
@Override
public void insert(Object entity) {
SqlPo sqlPo = this.getSqlPo(entity.getClass(), sqlCfg.getCamel());
SqlVal sqlVal = this.getSqlVal(sqlPo, entity);
String sql = this.getInsertSql(sqlPo);
if (sqlPo.getStrategy().equals(Constant.IDENTITY)) {
insertIdentity(sqlPo, sqlVal, entity, sql);
} else {
Object allVals[] = getInsertVals(sqlPo, sqlVal);
sqlCfg.getJdbcTemplate().update(sql, allVals);
}
}
private void insertIdentity(SqlPo sqlPo, SqlVal sqlVal, Object entity, final String sql) {
KeyHolder key = insertIdentityHandle(sql, sqlPo, sqlVal);
Number val = 0;
if (sqlPo.getKeyType() == Constant.INT) {
val = key.getKey().intValue();
} else {
val = key.getKey().longValue();
}
SqlUtil.setValue(entity, sqlPo.getCol2VarMap().get(sqlPo.getKey()), val);
}
private KeyHolder insertIdentityHandle(final String sql, final SqlPo sqlPo, final SqlVal sqlVal) {
Object allVals[] = getInsertVals(sqlPo, sqlVal);
KeyHolder key = new GeneratedKeyHolder();
sqlCfg.getJdbcTemplate().update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < allVals.length; i++) {
ps.setObject(i + 1, allVals[i]);
}
return ps;
}
}, key);
return key;
}
/**
*
*/
@Override
public int insertBatch(List
© 2015 - 2024 Weber Informatics LLC | Privacy Policy