package com.elab.core.spring.method;

import org.springframework.jdbc.core.PreparedStatementCreator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 为每个结果集加上Statement.RETURN_GENERATED_KEYS参数
 *
 * @author ： liukx
 * @time ： 2020/5/13 - 13:32
 */
public class BatchPreparedStatementCreator implements PreparedStatementCreator {
    private String[] generatedKeysColumnNames;
    private boolean returnGeneratedKeys = true;
    private String actualSql;

    public BatchPreparedStatementCreator(String actualSql) {
        this.actualSql = actualSql;
    }

    public void setGeneratedKeysColumnNames(String[] generatedKeysColumnNames) {
        this.generatedKeysColumnNames = generatedKeysColumnNames;
    }

    public void setReturnGeneratedKeys(boolean returnGeneratedKeys) {
        this.returnGeneratedKeys = returnGeneratedKeys;
    }

    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        PreparedStatement ps;
        if (generatedKeysColumnNames != null) {
            ps = con.prepareStatement(this.actualSql, generatedKeysColumnNames);
        } else {
            ps = con.prepareStatement(this.actualSql, PreparedStatement.RETURN_GENERATED_KEYS);
        }
        return ps;
    }
}
