|
6 | 6 | import java.util.List; |
7 | 7 |
|
8 | 8 | import org.baeldung.config.MongoConfig; |
| 9 | +import org.baeldung.model.EmailAddress; |
9 | 10 | import org.baeldung.model.User; |
10 | 11 | import org.junit.After; |
11 | 12 | import org.junit.Before; |
|
15 | 16 | import org.springframework.data.domain.PageRequest; |
16 | 17 | import org.springframework.data.domain.Pageable; |
17 | 18 | import org.springframework.data.domain.Sort; |
| 19 | +import org.springframework.data.domain.Sort.Direction; |
18 | 20 | import org.springframework.data.mongodb.core.MongoTemplate; |
| 21 | +import org.springframework.data.mongodb.core.index.Index; |
| 22 | +import org.springframework.data.mongodb.core.index.IndexInfo; |
19 | 23 | import org.springframework.data.mongodb.core.query.Criteria; |
20 | 24 | import org.springframework.data.mongodb.core.query.Query; |
21 | 25 | import org.springframework.test.context.ContextConfiguration; |
@@ -128,4 +132,42 @@ public void givenUsersExist_whenFindingUsersAndSortThem_thenUsersAreFoundAndSort |
128 | 132 | List<User> users = mongoTemplate.find(query, User.class); |
129 | 133 | assertThat(users.size(), is(3)); |
130 | 134 | } |
| 135 | + |
| 136 | + @Test |
| 137 | + public void givenUserExistsWithIndexAddedFromMapping_whenCheckingIndex_thenIndexIsExisted() { |
| 138 | + User user = new User(); |
| 139 | + user.setName("Brendan"); |
| 140 | + EmailAddress emailAddress = new EmailAddress(); |
| 141 | + emailAddress.setValue("a@gmail.com"); |
| 142 | + user.setEmailAddress(emailAddress); |
| 143 | + mongoTemplate.insert(user); |
| 144 | + |
| 145 | + List<IndexInfo> indexInfos = mongoTemplate.indexOps("user").getIndexInfo(); |
| 146 | + |
| 147 | + assertThat(indexInfos.size(), is(1)); |
| 148 | + } |
| 149 | + |
| 150 | + @Test |
| 151 | + public void givenExisted() { |
| 152 | + User user = new User(); |
| 153 | + user.setName("Brendan"); |
| 154 | + EmailAddress emailAddress = new EmailAddress(); |
| 155 | + emailAddress.setValue("b@gmail.com"); |
| 156 | + user.setEmailAddress(emailAddress); |
| 157 | + mongoTemplate.insert(user); |
| 158 | + |
| 159 | + assertThat(mongoTemplate.findOne(Query.query(Criteria.where("name").is("Brendan")), User.class).getEmailAddress().getValue(), is("b@gmail.com")); |
| 160 | + } |
| 161 | + |
| 162 | + @Test |
| 163 | + public void givenUserExistsWithIndexAddedFromCode_whenCheckingIndex_thenIndexIsExisted() { |
| 164 | + User user = new User(); |
| 165 | + user.setName("Brendan"); |
| 166 | + mongoTemplate.indexOps(User.class).ensureIndex(new Index().on("name", Direction.ASC)); |
| 167 | + mongoTemplate.insert(user); |
| 168 | + |
| 169 | + List<IndexInfo> indexInfos = mongoTemplate.indexOps("user").getIndexInfo(); |
| 170 | + |
| 171 | + assertThat(indexInfos.size(), is(2)); |
| 172 | + } |
131 | 173 | } |
0 commit comments