下面列出了java.sql.BatchUpdateException#getNextException ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Add a record in the table 'dataobjectrelations' for every resource, page,
* other dataobject, role and category associated to the given dataobject).
*
* @param dataobject The current dataobject.
* @param conn The connection to the database.
* @throws ApsSystemException when connection error are detected.
*/
protected void addDataObjectRelationsRecord(DataObject dataobject, Connection conn) throws ApsSystemException {
PreparedStatement stat = null;
try {
stat = conn.prepareStatement(ADD_DATAOBJECT_REL_RECORD);
this.addCategoryRelationsRecord(dataobject, true, stat);
this.addGroupRelationsRecord(dataobject, stat);
EntityAttributeIterator attributeIter = new EntityAttributeIterator(dataobject);
while (attributeIter.hasNext()) {
AttributeInterface currAttribute = (AttributeInterface) attributeIter.next();
}
stat.executeBatch();
} catch (BatchUpdateException e) {
_logger.error("Error saving record into dataobjectrelations {}", dataobject.getId(), e.getNextException());
throw new RuntimeException("Error saving record into dataobjectrelations " + dataobject.getId(), e.getNextException());
} catch (Throwable t) {
_logger.error("Error saving record into dataobjectrelations {}", dataobject.getId(), t);
throw new RuntimeException("Error saving record into dataobjectrelations " + dataobject.getId(), t);
} finally {
closeDaoResources(null, stat);
}
}
@Test
public void test_char_types_arrays() throws Exception {
try (Connection conn = DriverManager.getConnection(url(RW), properties)) {
conn.createStatement().executeUpdate(
"CREATE TABLE t (" +
" chars array(byte)," +
" strings array(text)) " +
"WITH (number_of_replicas = 0)");
PreparedStatement preparedStatement = conn.prepareStatement(
"INSERT INTO t (chars, strings) VALUES (?, ?)");
preparedStatement.setArray(1, conn.createArrayOf("char", new Byte[]{'c', '3'}));
preparedStatement.setArray(2, conn.createArrayOf("varchar", new String[]{"fo,o", "bar"}));
preparedStatement.executeUpdate();
conn.createStatement().execute("REFRESH TABLE t");
ResultSet resultSet = conn.createStatement().executeQuery("SELECT chars, strings FROM t");
assertThat(resultSet.next(), is(true));
assertThat(resultSet.getArray(1).getArray(), is(new String[]{"99", "51"}));
assertThat(resultSet.getArray(2).getArray(), is(new String[]{"fo,o", "bar"}));
} catch (BatchUpdateException e) {
throw e.getNextException();
}
}
@Test
public void test_numeric_types_arrays() throws Exception {
try (Connection conn = DriverManager.getConnection(url(RW), properties)) {
conn.createStatement().executeUpdate(
"CREATE TABLE t (" +
" ints array(int)," +
" floats array(float)" +
") " +
"WITH (number_of_replicas = 0)");
PreparedStatement preparedStatement = conn.prepareStatement(
"INSERT INTO t (ints, floats) VALUES (?, ?)");
preparedStatement.setArray(1, conn.createArrayOf("int4", new Integer[]{10, 20}));
preparedStatement.setArray(2, conn.createArrayOf("float4", new Float[]{1.2f, 3.5f}));
preparedStatement.executeUpdate();
conn.createStatement().execute("REFRESH TABLE t");
ResultSet rs = conn.createStatement().executeQuery("SELECT ints, floats FROM t");
assertThat(rs.next(), is(true));
assertThat(rs.getArray(1).getArray(), is(new Integer[]{10, 20}));
assertThat(rs.getArray(2).getArray(), is(new Float[]{1.2f, 3.5f}));
} catch (BatchUpdateException e) {
throw e.getNextException();
}
}
@Override
public SQLException call() throws IOException, SQLException, ClassNotFoundException {
if (rows.isEmpty()) {
return null;
}
boolean statementMustBeDeleted = false;
if (statement == null) {
statement = plugin.getPreparedStatement(plugin.getConnection(), query);
statementMustBeDeleted = true;
}
for (OneRow row : rows) {
JdbcResolver.decodeOneRowToPreparedStatement(row, statement);
statement.addBatch();
}
try {
statement.executeBatch();
}
catch (BatchUpdateException bue) {
SQLException cause = bue.getNextException();
return cause != null ? cause : bue;
}
catch (SQLException e) {
return e;
}
finally {
rows.clear();
if (statementMustBeDeleted) {
JdbcBasePlugin.closeStatementAndConnection(statement);
statement = null;
}
}
return null;
}
private void addLogRecordRelations(int recordId, ActivityStreamInfo asi, Connection conn) {
if (asi == null) {
return;
}
List<String> groups = asi.getGroups();
if (null == groups || groups.isEmpty()) {
return;
}
Set<String> codes = new HashSet<>(groups);
Iterator<String> iterator = codes.iterator();
PreparedStatement stat = null;
try {
stat = conn.prepareStatement(ADD_LOG_RECORD_RELATION);
while (iterator.hasNext()) {
String groupCode = iterator.next();
stat.setInt(1, recordId);
stat.setString(2, groupCode);
stat.addBatch();
stat.clearParameters();
}
stat.executeBatch();
} catch (BatchUpdateException e) {
logger.error("Error adding relation for record {}", recordId, e);
throw new RuntimeException("Error adding relation for record - " + recordId, e.getNextException());
} catch (Throwable t) {
logger.error("Error adding relations for record {}", recordId, t);
throw new RuntimeException("Error adding relations for record - " + recordId, t);
} finally {
closeDaoResources(null, stat);
}
}
private void addLabelGroup(String key, ApsProperties labels, Connection conn) throws ApsSystemException {
PreparedStatement stat = null;
try {
stat = conn.prepareStatement(ADD_LABEL);
Iterator<Object> labelKeysIter = labels.keySet().iterator();
while (labelKeysIter.hasNext()) {
String labelLangCode = (String) labelKeysIter.next();
String label = labels.getProperty(labelLangCode);
stat.setString(1, key);
stat.setString(2, labelLangCode);
stat.setString(3, label);
stat.addBatch();
stat.clearParameters();
}
stat.executeBatch();
} catch (BatchUpdateException e) {
_logger.error("Error adding a new label record", e.getNextException());
throw new RuntimeException("Error adding a new label record", e.getNextException());
//processDaoException(e.getNextException(), "Error adding a new label record", "addLabel");
} catch (Throwable t) {
_logger.error("Error while adding a new label", t);
throw new RuntimeException("Error while adding a new label", t);
//processDaoException(t, "Error while adding a new label", "addLabel");
} finally {
closeDaoResources(null, stat);
}
}
public void insert() throws SQLException {
try {
statement.executeBatch();
}
catch (BatchUpdateException e) {
throw e.getNextException();
}
finally {
statement.close();
}
}
/**
* Add a record in the table 'contentrelations' for every resource, page,
* other content, role and category associated to the given content).
*
* @param content
* The current content.
* @param conn
* The connection to the database.
* @throws ApsSystemException
* when connection error are detected.
*/
protected void addContentRelationsRecord(Content content, Connection conn) throws ApsSystemException {
PreparedStatement stat = null;
try {
stat = conn.prepareStatement(ADD_CONTENT_REL_RECORD);
this.addCategoryRelationsRecord(content, true, stat);
this.addGroupRelationsRecord(content, stat);
EntityAttributeIterator attributeIter = new EntityAttributeIterator(content);
while (attributeIter.hasNext()) {
AttributeInterface currAttribute = (AttributeInterface) attributeIter.next();
if (currAttribute instanceof IReferenceableAttribute) {
IReferenceableAttribute cmsAttribute = (IReferenceableAttribute) currAttribute;
List<CmsAttributeReference> refs = cmsAttribute.getReferences(this.getLangManager().getLangs());
for (int i = 0; i < refs.size(); i++) {
CmsAttributeReference ref = refs.get(i);
stat.setString(1, content.getId());
stat.setString(2, ref.getRefPage());
stat.setString(3, ref.getRefContent());
stat.setString(4, ref.getRefResource());
stat.setString(5, null);
stat.setString(6, null);
stat.addBatch();
stat.clearParameters();
}
}
}
stat.executeBatch();
} catch (BatchUpdateException e) {
_logger.error("Error saving record into contentrelations {}", content.getId(), e.getNextException());
throw new RuntimeException("Error saving record into contentrelations " + content.getId(), e.getNextException());
} catch (Throwable t) {
_logger.error("Error saving record into contentrelations {}", content.getId(), t);
throw new RuntimeException("Error saving record into contentrelations " + content.getId(), t);
} finally {
closeDaoResources(null, stat);
}
}
private void executeBatch(DataRecord[][] dataRecordHolder, int holderCount)
throws SQLException, IOException, InterruptedException, JetelException {
boolean exThrown = false;
String errmes = "";
DataRecord[] updatedRecord = null;
BatchUpdateException exception = null;
BatchUpdateException[] exceptions = new BatchUpdateException[statement.length];
boolean useSavepoints = connection.getJdbcSpecific().useSavepoints();
for (int statementCount = 0; statementCount < statement.length; statementCount++) {
try {
// Fix of issue #5711
if (useSavepoints && !atomicSQL) {
try {
savepoint = connection.setSavepoint(SAVEPOINT_NAME);
} catch (SQLException e) {
logger.warn("Failed to set SAVEPOINT; rest of transaction may be lost", e);
}
}
statement[statementCount].executeBatch();
updatedRecord = statement[statementCount].getBatchResult();
statement[statementCount].clearBatch();
} catch (BatchUpdateException ex) {
updatedRecord = statement[statementCount].getBatchResult();
statement[statementCount].clearBatch();
exceptions[statementCount] = ex;
exception = ex;
errmes += "Exception thrown by: " + statement[statementCount].getQuery() + ". Message: " + ExceptionUtils.getMessage(ex) + "\n";
if (ex.getNextException() != null) {
// With PostgreSQL, 1. exception is good for nothing, append next one
errmes += " Caused by: " + ExceptionUtils.getMessage(ex.getNextException());
}
exThrown = true;
if (useSavepoints && savepoint != null) {
connection.rollback(savepoint);
}
}
for (int i = 0; i < updatedRecord.length; i++) {
keysPort.writeRecord(updatedRecord[i]);
}
}
// all statements executed, some of them could fail
if (exThrown) {
failedBatches++;
countError++;
if (countError <= MAX_WARNINGS) {
logger.warn(errmes);
} else if (countError == MAX_WARNINGS + 1) {
logger.warn("more errors...");
}
flushErrorRecords(dataRecordHolder, holderCount, exceptions, rejectedPort);
if (atomicSQL) {
connection.rollback();
logger.info("Atomic SQL is true. Rollback performed.");
}
if (countError > maxErrors && maxErrors != -1) {
errorAction.perform(connection);
if (errorAction == ConnectionAction.ROLLBACK) {
logger.info("Rollback performed.");
logger.info("Number of commited records: " + (recCount / recordsInCommit) * recordsInCommit);
logger.info("Number of failed batches: " + failedBatches);
// logger.info("Last " + batchCount + " records not commited");
} else if (errorAction == ConnectionAction.COMMIT) {
logger.info("Number of commited records: " + ++recCount);
logger.info("Number of failed batches: " + failedBatches);
}
throw new JetelException("Maximum # of errors exceeded when executing batch. " + errmes, exception);
}
}
}
@Test
public void test_geo_types_arrays() throws Exception {
try (Connection conn = DriverManager.getConnection(url(RW), properties)) {
conn.createStatement().execute(
"CREATE TABLE t (" +
" geo_points array(geo_point)," +
" geo_shapes array(geo_shape)" +
") " +
"WITH (number_of_replicas = 0)");
PreparedStatement preparedStatement = conn.prepareStatement(
"INSERT INTO t (geo_points, geo_shapes) VALUES (?, ?)");
preparedStatement.setArray(1, conn.createArrayOf(
"point",
new PGpoint[]{new PGpoint(1.1, 2.2), new PGpoint(3.3, 4.4)}));
preparedStatement.setArray(2, conn.createArrayOf(
"json",
new Object[]{
DataTypes.STRING.value(
Map.of(
"coordinates", new double[][]{{0, 0}, {1, 1}},
"type", "LineString"
)
)
}));
preparedStatement.executeUpdate();
conn.createStatement().execute("REFRESH TABLE t");
ResultSet rs = conn.createStatement().executeQuery("SELECT geo_points, geo_shapes FROM t");
assertThat(rs.next(), is(true));
assertThat(
(Object[]) rs.getArray(1).getArray(),
arrayContaining(new PGpoint(1.1, 2.2), new PGpoint(3.3, 4.4)));
var shape = new PGobject();
shape.setType("json");
shape.setValue("{\"coordinates\":[[0.0,0.0],[1.0,1.0]],\"type\":\"LineString\"}");
assertThat((Object[]) rs.getArray(2).getArray(), arrayContaining(shape));
} catch (BatchUpdateException e) {
throw e.getNextException();
}
}