66import java .util .List ;
77
88import org .baeldung .config .MongoConfig ;
9+ import org .baeldung .model .EmailAddress ;
910import org .baeldung .model .User ;
1011import org .junit .After ;
1112import org .junit .Before ;
1516import org .springframework .data .domain .PageRequest ;
1617import org .springframework .data .domain .Pageable ;
1718import org .springframework .data .domain .Sort ;
19+ import org .springframework .data .domain .Sort .Direction ;
1820import org .springframework .data .mongodb .core .MongoTemplate ;
21+ import org .springframework .data .mongodb .core .index .Index ;
22+ import org .springframework .data .mongodb .core .index .IndexInfo ;
1923import org .springframework .data .mongodb .core .query .Criteria ;
2024import org .springframework .data .mongodb .core .query .Query ;
2125import org .springframework .test .context .ContextConfiguration ;
@@ -30,7 +34,9 @@ public class MongoTemplateQueryIntegrationTest {
3034
3135 @ Before
3236 public void testSetup () {
33- mongoTemplate .createCollection (User .class );
37+ if (!mongoTemplate .collectionExists (User .class )) {
38+ mongoTemplate .createCollection (User .class );
39+ }
3440 }
3541
3642 @ After
@@ -128,4 +134,42 @@ public void givenUsersExist_whenFindingUsersAndSortThem_thenUsersAreFoundAndSort
128134 List <User > users = mongoTemplate .find (query , User .class );
129135 assertThat (users .size (), is (3 ));
130136 }
137+
138+ @ Test
139+ public void givenUserExistsWithIndexAddedFromMapping_whenCheckingIndex_thenIndexIsExisted () {
140+ final User user = new User ();
141+ user .setName ("Brendan" );
142+ EmailAddress emailAddress = new EmailAddress ();
143+ emailAddress .setValue ("a@gmail.com" );
144+ user .setEmailAddress (emailAddress );
145+ mongoTemplate .insert (user );
146+
147+ List <IndexInfo > indexInfos = mongoTemplate .indexOps ("user" ).getIndexInfo ();
148+
149+ assertThat (indexInfos .size (), is (1 ));
150+ }
151+
152+ @ Test
153+ public void whenSavingUserWithEmailAddress_thenUserandEmailAddressSaved () {
154+ final User user = new User ();
155+ user .setName ("Brendan" );
156+ EmailAddress emailAddress = new EmailAddress ();
157+ emailAddress .setValue ("b@gmail.com" );
158+ user .setEmailAddress (emailAddress );
159+ mongoTemplate .insert (user );
160+
161+ assertThat (mongoTemplate .findOne (Query .query (Criteria .where ("name" ).is ("Brendan" )), User .class ).getEmailAddress ().getValue (), is ("b@gmail.com" ));
162+ }
163+
164+ @ Test
165+ public void givenUserExistsWithIndexAddedFromCode_whenCheckingIndex_thenIndexIsExisted () {
166+ final User user = new User ();
167+ user .setName ("Brendan" );
168+ mongoTemplate .indexOps (User .class ).ensureIndex (new Index ().on ("name" , Direction .ASC ));
169+ mongoTemplate .insert (user );
170+
171+ List <IndexInfo > indexInfos = mongoTemplate .indexOps ("user" ).getIndexInfo ();
172+
173+ assertThat (indexInfos .size (), is (2 ));
174+ }
131175}
0 commit comments