Skip to content
Open
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
4b65eb2
Introduce batch support.
vbabanin Sep 11, 2025
5b17d58
Add tests and refactor MongoStatements.
vbabanin Oct 2, 2025
3f1ebcb
Merge branch 'main' into HIBERNATE-40
vbabanin Oct 2, 2025
ded2bb7
Rename tests.
vbabanin Oct 2, 2025
92d9c41
Rename variables.
vbabanin Oct 2, 2025
b78cb77
Rename methods, add tests.
vbabanin Oct 2, 2025
a7f7792
Revert to private.
vbabanin Oct 2, 2025
7372d56
Add JDBC exception handling.
vbabanin Oct 7, 2025
330de0f
Apply spotless.
vbabanin Oct 7, 2025
5c81496
Apply spotless.
vbabanin Oct 7, 2025
e4d7afd
Revert SqlTransientException handling.
vbabanin Oct 8, 2025
183aafc
Remove SQlConsumer.
vbabanin Oct 8, 2025
9577603
Fix issues.
vbabanin Oct 21, 2025
76acbc5
Update src/integrationTest/java/com/mongodb/hibernate/jdbc/MongoPrepa…
vbabanin Oct 25, 2025
39df511
Update src/integrationTest/java/com/mongodb/hibernate/jdbc/MongoPrepa…
vbabanin Oct 25, 2025
11a2b07
Update src/integrationTest/java/com/mongodb/hibernate/jdbc/MongoPrepa…
vbabanin Oct 25, 2025
510bc2d
Update src/integrationTest/java/com/mongodb/hibernate/jdbc/MongoPrepa…
vbabanin Oct 27, 2025
6faa9cb
Fix batch update count reporting.
vbabanin Oct 28, 2025
b27ef0e
Merge branch 'main' into HIBERNATE-40
vbabanin Oct 28, 2025
7c8a702
Make NULL_SQL_STATE private.
vbabanin Oct 28, 2025
51103be
Remove final in parameters.
vbabanin Oct 28, 2025
4317e2f
Remove catch.
vbabanin Oct 28, 2025
2b5be78
Use constants.
vbabanin Oct 28, 2025
40c75cf
Remove accidental use of NO_ERROR_CODE.
vbabanin Oct 28, 2025
91a88f1
Consolidate batch execution logic in one place.
vbabanin Oct 28, 2025
9435785
Remove redundunt methods.
vbabanin Oct 28, 2025
46d4682
Update src/main/java/com/mongodb/hibernate/jdbc/MongoStatement.java
vbabanin Oct 28, 2025
afd8853
Update src/main/java/com/mongodb/hibernate/jdbc/MongoStatement.java
vbabanin Oct 28, 2025
18a18f7
Apply suggestions from code review
vbabanin Oct 29, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ protected <T> void assertSelectionQuery(
}
var resultList = selectionQuery.getResultList();

assertActualCommand(BsonDocument.parse(expectedMql));
assertActualCommandsInOrder(BsonDocument.parse(expectedMql));

resultListVerifier.accept(resultList);

Expand Down Expand Up @@ -178,13 +178,13 @@ protected void assertSelectQueryFailure(
expectedExceptionMessageParameters);
}

protected void assertActualCommand(BsonDocument expectedCommand) {
protected void assertActualCommandsInOrder(BsonDocument... expectedCommands) {
var capturedCommands = testCommandListener.getStartedCommands();

assertThat(capturedCommands)
.singleElement()
.asInstanceOf(InstanceOfAssertFactories.MAP)
.containsAllEntriesOf(expectedCommand);
assertThat(capturedCommands).hasSize(expectedCommands.length);
for (int i = 0; i < expectedCommands.length; i++) {
BsonDocument actual = capturedCommands.get(i);
assertThat(actual).asInstanceOf(InstanceOfAssertFactories.MAP).containsAllEntriesOf(expectedCommands[i]);
}
}

protected void assertMutationQuery(
Expand All @@ -201,7 +201,7 @@ protected void assertMutationQuery(
queryPostProcessor.accept(query);
}
var mutationCount = query.executeUpdate();
assertActualCommand(BsonDocument.parse(expectedMql));
assertActualCommandsInOrder(BsonDocument.parse(expectedMql));
assertThat(mutationCount).isEqualTo(expectedMutationCount);
});
assertThat(collection.find()).containsExactlyElementsOf(expectedDocuments);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
/*
* Copyright 2025-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.mongodb.hibernate.query.mutation;

import static org.assertj.core.api.Assertions.assertThat;
import static org.bson.RawBsonDocument.parse;

import com.mongodb.client.MongoCollection;
import com.mongodb.hibernate.junit.InjectMongoCollection;
import com.mongodb.hibernate.query.AbstractQueryIntegrationTests;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.util.List;
import org.bson.BsonDocument;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.testing.orm.junit.DomainModel;
import org.hibernate.testing.orm.junit.ServiceRegistry;
import org.hibernate.testing.orm.junit.Setting;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

@DomainModel(annotatedClasses = BatchUpdateIntegrationTests.Item.class)
@ServiceRegistry(settings = @Setting(name = AvailableSettings.STATEMENT_BATCH_SIZE, value = "3"))
class BatchUpdateIntegrationTests extends AbstractQueryIntegrationTests {

private static final String COLLECTION_NAME = "items";
private static final int ENTITIES_TO_PERSIST_COUNT = 5;

@InjectMongoCollection(COLLECTION_NAME)
private static MongoCollection<BsonDocument> collection;

@BeforeEach
void beforeEach() {
getTestCommandListener().clear();
}

@Test
void testBatchInsert() {
getSessionFactoryScope().inTransaction(session -> {
for (int i = 1; i <= ENTITIES_TO_PERSIST_COUNT; i++) {
session.persist(new Item(i, String.valueOf(i)));
}
session.flush();
assertActualCommandsInOrder(
parse(
"""
{
"insert": "items",
"ordered": true,
"documents": [
{ "_id": 1, "string": "1"},
{ "_id": 2, "string": "2"},
{ "_id": 3, "string": "3"}
]
}
"""),
parse(
"""
{
"insert": "items",
"ordered": true,
"documents": [
{ "_id": 4, "string": "4"},
{ "_id": 5, "string": "5"}
]
}
"""));
});

assertThat(collection.find())
.containsExactlyElementsOf(List.of(
BsonDocument.parse("{ _id: 1, string: '1' }"),
BsonDocument.parse("{ _id: 2, string: '2' }"),
BsonDocument.parse("{ _id: 3, string: '3' }"),
BsonDocument.parse("{ _id: 4, string: '4' }"),
BsonDocument.parse("{ _id: 5, string: '5' }")));
}

@Test
void testBatchUpdate() {
getSessionFactoryScope().inTransaction(session -> {
insertTestData(session);
for (int i = 1; i <= ENTITIES_TO_PERSIST_COUNT; i++) {
Item item = session.find(Item.class, i);
item.string = "u" + i;
}
session.flush();
assertActualCommandsInOrder(
parse(
"""
{
"update": "items",
"ordered": true,
"updates": [
{ "q": { "_id": { "$eq": 1 } }, "u": { "$set": { "string": "u1" } }, "multi": true },
{ "q": { "_id": { "$eq": 2 } }, "u": { "$set": { "string": "u2" } }, "multi": true },
{ "q": { "_id": { "$eq": 3 } }, "u": { "$set": { "string": "u3" } }, "multi": true }
]
}
"""),
parse(
"""
{
"update": "items",
"ordered": true,
"updates": [
{ "q": { "_id": { "$eq": 4 } }, "u": { "$set": { "string": "u4" } }, "multi": true },
{ "q": { "_id": { "$eq": 5 } }, "u": { "$set": { "string": "u5" } }, "multi": true }
]
}
"""));
});

assertThat(collection.find())
.containsExactlyElementsOf(java.util.List.of(
BsonDocument.parse("{ _id: 1, string: 'u1' }"),
BsonDocument.parse("{ _id: 2, string: 'u2' }"),
BsonDocument.parse("{ _id: 3, string: 'u3' }"),
BsonDocument.parse("{ _id: 4, string: 'u4' }"),
BsonDocument.parse("{ _id: 5, string: 'u5' }")));
}

@Test
void testBatchDelete() {
getSessionFactoryScope().inTransaction(session -> {
insertTestData(session);
for (int i = 1; i <= ENTITIES_TO_PERSIST_COUNT; i++) {
var item = session.find(Item.class, i);
session.remove(item);
}
session.flush();
assertActualCommandsInOrder(
parse(
"""
{
"delete": "items",
"ordered": true,
"deletes": [
{"q": {"_id": {"$eq": 1}}, "limit": 0},
{"q": {"_id": {"$eq": 2}}, "limit": 0},
{"q": {"_id": {"$eq": 3}}, "limit": 0}
]
}
"""),
parse(
"""
{
"delete": "items",
"ordered": true,
"deletes": [
{"q": {"_id": {"$eq": 4}}, "limit": 0},
{"q": {"_id": {"$eq": 5}}, "limit": 0}
]
}
"""));
});

assertThat(collection.find()).isEmpty();
}

private void insertTestData(final SessionImplementor session) {
for (int i = 1; i <= 5; i++) {
session.persist(new Item(i, String.valueOf(i)));
}
session.flush();
getTestCommandListener().clear();
}

@Entity
@Table(name = COLLECTION_NAME)
static class Item {
@Id
int id;

String string;

Item() {}

Item(int id, String string) {
this.id = id;
this.string = string;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -614,7 +614,7 @@ private void setQueryOptionsAndQuery(
query.getResultList();
if (expectedMql != null) {
var expectedCommand = BsonDocument.parse(expectedMql);
assertActualCommand(expectedCommand);
assertActualCommandsInOrder(expectedCommand);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,20 @@
import com.mongodb.hibernate.internal.type.ObjectIdJdbcType;
import java.math.BigDecimal;
import java.sql.Array;
import java.sql.BatchUpdateException;
import java.sql.Date;
import java.sql.JDBCType;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLSyntaxErrorException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
Expand All @@ -52,15 +55,16 @@
final class MongoPreparedStatement extends MongoStatement implements PreparedStatementAdapter {

private final BsonDocument command;

private final List<BsonDocument> commandBatch;
private final List<ParameterValueSetter> parameterValueSetters;

MongoPreparedStatement(
MongoDatabase mongoDatabase, ClientSession clientSession, MongoConnection mongoConnection, String mql)
throws SQLSyntaxErrorException {
super(mongoDatabase, clientSession, mongoConnection);
this.command = MongoStatement.parse(mql);
this.parameterValueSetters = new ArrayList<>();
command = MongoStatement.parse(mql);
commandBatch = new ArrayList<>();
parameterValueSetters = new ArrayList<>();
parseParameters(command, parameterValueSetters);
}

Expand All @@ -77,6 +81,7 @@ public int executeUpdate() throws SQLException {
checkClosed();
closeLastOpenResultSet();
checkAllParametersSet();
checkSupportedUpdateCommand(command);
return executeUpdateCommand(command);
}

Expand Down Expand Up @@ -200,7 +205,49 @@ public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQ
@Override
public void addBatch() throws SQLException {
checkClosed();
throw new SQLFeatureNotSupportedException("TODO-HIBERNATE-35 https://jira.mongodb.org/browse/HIBERNATE-35");
checkAllParametersSet();
commandBatch.add(command.clone());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[optional]

This check may not help us at all, as batching parameterless commands is hardly practical, but neither will it hurt, and it makes it clear that we have to clone specifically because of the parameter value setters.

Suggested change
commandBatch.add(command.clone());
commandBatch.add(parameterValueSetters.isEmpty() ? command : command.clone());

}

@Override
public void clearBatch() throws SQLException {
checkClosed();
commandBatch.clear();
}

@Override
public int[] executeBatch() throws SQLException {
checkClosed();
closeLastOpenResultSet();
if (commandBatch.isEmpty()) {
return EMPTY_BATCH_RESULT;
}
checkSupportedBatchCommand(commandBatch.get(0));
try {
executeBulkWrite(commandBatch, ExecutionType.BATCH);
var updateCounts = new int[commandBatch.size()];
// We cannot determine the actual number of rows affected for each command in the batch.
Arrays.fill(updateCounts, Statement.SUCCESS_NO_INFO);
return updateCounts;
} finally {
commandBatch.clear();
}
}

private void checkSupportedBatchCommand(BsonDocument command) throws SQLException {
var commandType = getCommandType(command);
if (commandType == CommandType.AGGREGATE) {
// The method executeBatch throws a BatchUpdateException if any of the commands in the batch attempts to
// return a result set.
throw new BatchUpdateException(
format(
"Commands returning result set are not supported. Received command: %s",
commandType.getCommandName()),
null,
NO_ERROR_CODE,
null);
}
checkSupportedUpdateCommand(commandType);
}

@Override
Expand Down
Loading