Elffuss BraidHub

kikocis/java-driver public

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