Elffuss BraidHub

kikocis/java-driver public

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