Elffuss BraidHub

kikocis/java-driver public

fda4a447ecf4 · 15.3 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2015 DataStax Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.datastax.driver.mapping;
17
18import java.net.InetAddress;
19
20import com.datastax.driver.core.utils.CassandraVersion;
21import com.datastax.driver.mapping.annotations.Table;
22import java.util.*;
23
24import com.google.common.base.Objects;
25import com.google.common.util.concurrent.ListenableFuture;
26import org.testng.annotations.Test;
27
28import static org.assertj.core.api.Assertions.assertThat;
29import static org.testng.Assert.*;
30
31import com.datastax.driver.mapping.MapperTest.User.Gender;
32import com.datastax.driver.mapping.annotations.*;
33import com.datastax.driver.core.*;
34import com.datastax.driver.core.utils.UUIDs;
35
36/**
37 * Basic tests for the mapping module.
38 */
39public class MapperTest extends CCMBridge.PerClassSingleNodeCluster {
40
41 protected Collection<String> getTableDefinitions() {
42 // We'll allow to generate those create statement from the annotated entities later, but it's currently
43 // a TODO
44 return Arrays.asList("CREATE TABLE users (user_id uuid PRIMARY KEY, name text, email text, year int, gender text)",
45 "CREATE TABLE posts (user_id uuid, post_id timeuuid, title text, content text, device inet, tags set<text>, PRIMARY KEY(user_id, post_id))");
46 }
47
48 /*
49 * Annotates a simple entity. Not a whole lot to see here, all fields are
50 * mapped by default (but there is a @Transcient to have a field non mapped)
51 * to a C* column that have the same name than the field (but you can use @Column
52 * to specify the actual column name in C* if it's different).
53 *
54 * Do note that we support enums (which are mapped to strings by default
55 * but you can map them to their ordinal too with some @Enumerated annotation)
56 *
57 * And the next step will be to support UDT (which should be relatively simple).
58 */
59 @Table(name = "users",
60 readConsistency="QUORUM",
61 writeConsistency="QUORUM")
62 public static class User {
63
64 // Dummy constant to test that static fields are properly ignored
65 public static final int FOO = 1;
66
67 public enum Gender { FEMALE, MALE }
68
69 @PartitionKey
70 @Column(name = "user_id")
71 private UUID userId;
72
73 private String name;
74 private String email;
75 @Column // not strictly required, but we want to check that the annotation works without a name
76 private int year;
77
78 private Gender gender;
79
80 public User() {}
81
82 public User(String name, String email, Gender gender) {
83 this.userId = UUIDs.random();
84 this.name = name;
85 this.email = email;
86 this.gender = gender;
87 }
88
89 public UUID getUserId() {
90 return userId;
91 }
92
93 public void setUserId(UUID userId) {
94 this.userId = userId;
95 }
96
97 public String getName() {
98 return name;
99 }
100
101 public void setName(String name) {
102 this.name = name;
103 }
104
105 public String getEmail() {
106 return email;
107 }
108
109 public void setEmail(String email) {
110 this.email = email;
111 }
112
113 public int getYear() {
114 return year;
115 }
116
117 public void setGender(Gender gender) {
118 this.gender = gender;
119 }
120
121 public Gender getGender() {
122 return gender;
123 }
124
125 public void setYear(int year) {
126 this.year = year;
127 }
128
129 @Override
130 public boolean equals(Object other) {
131 if (other == null || other.getClass() != this.getClass())
132 return false;
133
134 User that = (User)other;
135 return Objects.equal(userId, that.userId)
136 && Objects.equal(name, that.name)
137 && Objects.equal(email, that.email)
138 && Objects.equal(year, that.year)
139 && Objects.equal(gender, that.gender);
140 }
141
142 @Override
143 public int hashCode() {
144 return Objects.hashCode(userId, name, email, year, gender);
145 }
146 }
147
148 /*
149 * Another annotated entity, but that correspond to a table that has a
150 * clustering column. Note that if there is more than one clustering column,
151 * the order must be specified (@ClusteringColumn(0), @ClusteringColumn(1), ...).
152 * The same stands for the @PartitionKey.
153 */
154 @Table(name = "posts")
155 public static class Post {
156
157 @PartitionKey
158 @Column(name = "user_id")
159 private UUID userId;
160
161 @ClusteringColumn
162 @Column(name = "post_id")
163 private UUID postId;
164
165 private String title;
166 private String content;
167 private InetAddress device;
168
169 private Set<String> tags;
170
171 public Post() {}
172
173 public Post(User user, String title) {
174 this.userId = user.getUserId();
175 this.postId = UUIDs.timeBased();
176 this.title = title;
177 }
178
179 public UUID getUserId() {
180 return userId;
181 }
182
183 public void setUserId(UUID userId) {
184 this.userId = userId;
185 }
186
187 public UUID getPostId() {
188 return postId;
189 }
190
191 public void setPostId(UUID postId) {
192 this.postId = postId;
193 }
194
195 public String getTitle() {
196 return title;
197 }
198
199 public void setTitle(String title) {
200 this.title = title;
201 }
202
203 public String getContent() {
204 return content;
205 }
206
207 public void setContent(String content) {
208 this.content = content;
209 }
210
211 public InetAddress getDevice() {
212 return device;
213 }
214
215 public void setDevice(InetAddress device) {
216 this.device = device;
217 }
218
219 public Set<String> getTags() {
220 return tags;
221 }
222
223 public void setTags(Set<String> tags) {
224 this.tags = tags;
225 }
226
227 @Override
228 public boolean equals(Object other) {
229 if (other == null || other.getClass() != this.getClass())
230 return false;
231
232 Post that = (Post)other;
233 return Objects.equal(userId, that.userId)
234 && Objects.equal(postId, that.postId)
235 && Objects.equal(title, that.title)
236 && Objects.equal(content, that.content)
237 && Objects.equal(device, that.device)
238 && Objects.equal(tags, that.tags);
239 }
240
241 @Override
242 public int hashCode() {
243 return Objects.hashCode(userId, postId, title, content, device, tags);
244 }
245 }
246
247 /*
248 * We actually have 2 concepts in the mapping module. The first is the
249 * mapping of entities like User and Post above. From such annotated entity
250 * you can get a Mapper object (see below), which allow to map the Row of
251 * ResultSet to proper object, and that provide a few simple method like
252 * save, delete and a simple get.
253 *
254 * But to remove a bit of boilerplate when you need more complex queries, we
255 * also have the concept of Accesor, which is just a way to associate some
256 * java method calls to queries. Note that you don't have to use those Accessor
257 * if you don't want (and in fact, you can use the Accessor concept even if
258 * you don't map any entity).
259 */
260 @Accessor
261 public interface PostAccessor {
262 // Note that for implementation reasons, this *needs* to be an interface.
263
264 // The @Param below is because you can't get the name of parameters of methods
265 // by reflection (you can only have their types), so you have to annotate them
266 // if you want to give them proper names in the query. That being said, if you
267 // don't have @Param annotation like in the 2 other method, we default to some
268 // harcoded arg0, arg1, .... A big annoying, and apparently Java 8 will fix that
269 // somehow, but well, not a huge deal.
270 @Query("SELECT * FROM posts WHERE user_id=:userId AND post_id=:postId")
271 public Post getOne(@Param("userId") UUID userId,
272 @Param("postId") UUID postId);
273
274 // Note that the following method will be asynchronous (it will use executeAsync
275 // underneath) because it's return type is a ListenableFuture. Similarly, we know
276 // that we need to map the result to the Post entity thanks to the return type.
277 @Query("SELECT * FROM posts WHERE user_id=?")
278 @QueryParameters(consistency="QUORUM")
279 public ListenableFuture<Result<Post>> getAllAsync(UUID userId);
280
281 // The method above actually query stuff, but if a method is declared to return
282 // a Statement, it will not execute anything, but just return you the BoundStatement
283 // ready for execution. That way, you can batch stuff for instance (see usage below).
284 @Query("UPDATE posts SET content=? WHERE user_id=? AND post_id=?")
285 public Statement updateContentQuery(String newContent, UUID userId, UUID postId);
286
287 @Query("SELECT * FROM posts")
288 public Result<Post> getAll();
289 }
290
291 @Accessor
292 public interface UserAccessor {
293 // Demonstrates use of an enum as an accessor parameter
294 @Query("UPDATE users SET name=?, gender=? WHERE user_id=?")
295 ResultSet updateNameAndGender(String name, Gender gender, UUID userId);
296 }
297
298 @Test(groups = "short")
299 public void testStaticEntity() throws Exception {
300 // Very simple mapping a User, saving and getting it. Note that here we
301 // don't use the Accessor stuff since the queries we use are directly
302 // supported by the Mapper object.
303 Mapper<User> m = new MappingManager(session).mapper(User.class);
304
305 User u1 = new User("Paul", "paul@yahoo.com", User.Gender.MALE);
306 u1.setYear(2014);
307 m.save(u1);
308
309 // Do note that m.get() takes the primary key of what we want to fetch
310 // in argument, it doesn't not take a User object because we don't proxy
311 // objects `a la' SpringData/Hibernate. The reason for not doing that
312 // is that we don't want to encourage read-before-write.
313 assertEquals(m.get(u1.getUserId()), u1);
314 }
315
316 @Test(groups = "short")
317 @CassandraVersion(major=2.0)
318 public void testDynamicEntity() throws Exception {
319 MappingManager manager = new MappingManager(session);
320
321 Mapper<Post> m = manager.mapper(Post.class);
322
323 User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
324 Post p1 = new Post(u1, "Something about mapping");
325 Post p2 = new Post(u1, "Something else");
326 Post p3 = new Post(u1, "Something more");
327
328 p1.setDevice(InetAddress.getLocalHost());
329
330 p2.setTags(new HashSet<String>(Arrays.asList("important", "keeper")));
331
332 m.save(p1);
333 m.save(p2);
334 m.save(p3);
335
336 // Creates the accessor proxy defined above
337 PostAccessor postAccessor = manager.createAccessor(PostAccessor.class);
338
339 // Note that getOne is really the same than m.get(), it's just there
340 // for demonstration sake.
341 Post p = postAccessor.getOne(p1.getUserId(), p1.getPostId());
342 assertEquals(p, p1);
343
344 Result<Post> r = postAccessor.getAllAsync(p1.getUserId()).get();
345 assertEquals(r.one(), p1);
346 assertEquals(r.one(), p2);
347 assertEquals(r.one(), p3);
348 assertTrue(r.isExhausted());
349
350 // No argument call
351 r = postAccessor.getAll();
352 assertEquals(r.one(), p1);
353 assertEquals(r.one(), p2);
354 assertEquals(r.one(), p3);
355 assertTrue(r.isExhausted());
356
357 BatchStatement batch = new BatchStatement();
358 batch.add(postAccessor.updateContentQuery("Something different", p1.getUserId(), p1.getPostId()));
359 batch.add(postAccessor.updateContentQuery("A different something", p2.getUserId(), p2.getPostId()));
360 manager.getSession().execute(batch);
361
362 Post p1New = m.get(p1.getUserId(), p1.getPostId());
363 assertEquals(p1New.getContent(), "Something different");
364 Post p2New = m.get(p2.getUserId(), p2.getPostId());
365 assertEquals(p2New.getContent(), "A different something");
366
367 m.delete(p1);
368 m.delete(p2);
369
370 // Check delete by primary key too
371 m.delete(p3.getUserId(), p3.getPostId());
372
373 assertTrue(postAccessor.getAllAsync(u1.getUserId()).get().isExhausted());
374
375 // Pass an enum constant as an accessor parameter
376 UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
377 userAccessor.updateNameAndGender("Paule", User.Gender.FEMALE, u1.getUserId());
378 Mapper<User> userMapper = manager.mapper(User.class);
379 assertEquals(userMapper.get(u1.getUserId()).getGender(), User.Gender.FEMALE);
380
381 // Test that an enum value can be unassigned through an accessor (set to null).
382 userAccessor.updateNameAndGender("Paule", null, u1.getUserId());
383 assertEquals(userMapper.get(u1.getUserId()).getGender(), null);
384 }
385
386 @Test(groups="short")
387 public void should_map_objects_from_partial_queries() throws Exception {
388 MappingManager manager = new MappingManager(session);
389
390 Mapper<Post> m = manager.mapper(Post.class);
391
392 // Insert a few posts
393 User u1 = new User("Paul", "paul@gmail.com", User.Gender.MALE);
394 Post p1 = new Post(u1, "Something about mapping");
395 Post p2 = new Post(u1, "Something else");
396 Post p3 = new Post(u1, "Something more");
397
398 p1.setDevice(InetAddress.getLocalHost());
399 p2.setTags(new HashSet<String>(Arrays.asList("important", "keeper")));
400
401 m.save(p1);
402 m.save(p2);
403 m.save(p3);
404
405 // Retrieve posts with a projection query that only retrieves some of the fields
406 ResultSet rs = session.execute("select user_id, post_id, title from posts where user_id = " + u1.getUserId());
407
408 Result<Post> result = m.map(rs);
409 for (Post post : result) {
410 assertThat(post.getUserId()).isEqualTo(u1.getUserId());
411 assertThat(post.getPostId()).isNotNull();
412 assertThat(post.getTitle()).isNotNull();
413
414 assertThat(post.getDevice()).isNull();
415 assertThat(post.getTags()).isNull();
416 }
417
418 // cleanup
419 session.execute("delete from posts where user_id = " + u1.getUserId());
420 }
421
422 @Test(groups="short")
423 public void should_not_initialize_session_when_protocol_version_provided() {
424 Session newSession = cluster.newSession();
425
426 // Ensures that a Session is not initialized when a protocol version is provided.
427 MappingManager manager = new MappingManager(newSession, ProtocolVersion.V1);
428 assertThat(newSession.getState().getConnectedHosts()).hasSize(0);
429
430 // Session should be initialized on first query.
431 newSession.execute("USE " + keyspace);
432 assertThat(newSession.getState().getConnectedHosts()).hasSize(1);
433 }
434}