3131import jakarta .persistence .FlushModeType ;
3232
3333import com .mongodb .MongoClientSettings ;
34+ import com .mongodb .MongoCommandException ;
3435import com .mongodb .client .MongoClient ;
3536import com .mongodb .client .MongoIterable ;
3637import com .mongodb .client .model .IndexOptions ;
@@ -846,7 +847,11 @@ protected void initializeIndices(final PersistentEntity entity) {
846847 for (MongoCollection .Index index : indices ) {
847848 final Map <String , Object > options = index .getOptions ();
848849 final IndexOptions indexOptions = MongoConstants .mapToObject (IndexOptions .class , options );
849- collection .createIndex (new Document (index .getDefinition ()), indexOptions );
850+ try {
851+ collection .createIndex (new Document (index .getDefinition ()), indexOptions );
852+ } catch (MongoCommandException e ) {
853+ LOG .error ("Failed to create index for entity [" + entity .getName () + "] with definition [" + index .getDefinition () + "]: " + e .getMessage (), e );
854+ }
850855 }
851856
852857 for (Map compoundIndex : mappedForm .getCompoundIndices ()) {
@@ -859,11 +864,15 @@ protected void initializeIndices(final PersistentEntity entity) {
859864 }
860865 }
861866 Document indexDef = new Document (compoundIndex );
862- if (indexAttributes != null ) {
863- final IndexOptions indexOptions = MongoConstants .mapToObject (IndexOptions .class , indexAttributes );
864- collection .createIndex (indexDef , indexOptions );
865- } else {
866- collection .createIndex (indexDef );
867+ try {
868+ if (indexAttributes != null ) {
869+ final IndexOptions indexOptions = MongoConstants .mapToObject (IndexOptions .class , indexAttributes );
870+ collection .createIndex (indexDef , indexOptions );
871+ } else {
872+ collection .createIndex (indexDef );
873+ }
874+ } catch (MongoCommandException e ) {
875+ LOG .error ("Failed to create compound index for entity [" + entity .getName () + "] with definition [" + indexDef + "]: " + e .getMessage (), e );
867876 }
868877 }
869878 }
@@ -889,11 +898,15 @@ protected void initializeIndices(final PersistentEntity entity) {
889898 }
890899 }
891900 // continue using deprecated method to support older versions of MongoDB
892- if (options .isEmpty ()) {
893- collection .createIndex (dbObject );
894- } else {
895- final IndexOptions indexOptions = MongoConstants .mapToObject (IndexOptions .class , options );
896- collection .createIndex (dbObject , indexOptions );
901+ try {
902+ if (options .isEmpty ()) {
903+ collection .createIndex (dbObject );
904+ } else {
905+ final IndexOptions indexOptions = MongoConstants .mapToObject (IndexOptions .class , options );
906+ collection .createIndex (dbObject , indexOptions );
907+ }
908+ } catch (MongoCommandException e ) {
909+ LOG .error ("Failed to create index for entity [" + entity .getName () + "] on property [" + property .getName () + "]: " + e .getMessage (), e );
897910 }
898911 }
899912 }
0 commit comments