Elffuss BraidHub

kikocis/java-driver public

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