Elffuss BraidHub

kikocis/java-driver public

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