Elffuss BraidHub

kikocis/java-driver public

299d3531632f · 5.9 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.examples.json;
17
18import com.datastax.driver.core.*;
19import com.datastax.driver.extras.codecs.json.JacksonJsonCodec;
20import com.fasterxml.jackson.annotation.JsonCreator;
21import com.fasterxml.jackson.annotation.JsonProperty;
22
23import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
24
25/**
26 * Illustrates how to map an entire table row to a Java object using
27 * the <a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a> library,
28 * and leveraging the {@code SELECT JSON} and {@code INSERT JSON} syntaxes
29 * introduced in Cassandra 2.2.
30 * <p/>
31 * This example makes usage of a custom {@link TypeCodec codec},
32 * {@link JacksonJsonCodec}, which is declared in the driver-extras module.
33 * If you plan to follow this example, make sure to include the following
34 * Maven dependencies in your project:
35 * <pre>{@code
36 * <dependency>
37 * <groupId>com.datastax.cassandra</groupId>
38 * <artifactId>cassandra-driver-extras</artifactId>
39 * <version>${driver.version}</version>
40 * </dependency>
41 *
42 * <dependency>
43 * <groupId>com.fasterxml.jackson.core</groupId>
44 * <artifactId>jackson-databind</artifactId>
45 * <version>${jackson.version}</version>
46 * </dependency>
47 * }</pre>
48 * This example also uses the {@link com.datastax.driver.core.querybuilder.QueryBuilder QueryBuilder};
49 * for examples using the "core" API, see {@link PlainTextJson} (they are easily translatable to the
50 * queries in this class).
51 * <p/>
52 * Preconditions:
53 * - a Cassandra 2.2+ cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT;
54 * <p/>
55 * Side effects:
56 * - creates a new keyspace "examples" in the cluster. If a keyspace with this name already exists, it will be reused;
57 * - creates a table "examples.json_jackson_row". If it already exists, it will be reused;
58 * - inserts data in the table.
59 *
60 * @see <a href="http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-2-json-support">What’s New in Cassandra 2.2: JSON Support</a>
61 */
62public class JacksonJsonRow {
63
64 static String[] CONTACT_POINTS = {"127.0.0.1"};
65 static int PORT = 9042;
66
67 public static void main(String[] args) {
68 Cluster cluster = null;
69 try {
70
71 // A codec to convert JSON payloads into User instances;
72 // this codec is declared in the driver-extras module
73 TypeCodec<User> userCodec = new JacksonJsonCodec<User>(User.class);
74
75 cluster = Cluster.builder()
76 .addContactPoints(CONTACT_POINTS).withPort(PORT)
77 .withCodecRegistry(new CodecRegistry().register(userCodec))
78 .build();
79
80 Session session = cluster.connect();
81
82 createSchema(session);
83 insertJsonRow(session);
84 selectJsonRow(session);
85
86 } finally {
87 if (cluster != null) cluster.close();
88 }
89 }
90
91 private static void createSchema(Session session) {
92 session.execute("CREATE KEYSPACE IF NOT EXISTS examples " +
93 "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
94 session.execute("CREATE TABLE IF NOT EXISTS examples.json_jackson_row(" +
95 "id int PRIMARY KEY, name text, age int)");
96 }
97
98 // Mapping a User instance to a table row using INSERT JSON
99 private static void insertJsonRow(Session session) {
100 // Build and execute a simple statement
101 Statement stmt = insertInto("examples", "json_jackson_row")
102 .json(new User(1, "alice", 30));
103 session.execute(stmt);
104
105 // The JSON object can be a bound value if the statement is prepared
106 // (we use a local variable here for the sake of example, but in a real application you would cache and reuse
107 // the prepared statement)
108 PreparedStatement pst = session.prepare(
109 insertInto("examples", "json_jackson_row").json(bindMarker("user")));
110 session.execute(pst.bind()
111 .set("user", new User(2, "bob", 35), User.class));
112 }
113
114 // Retrieving User instances from table rows using SELECT JSON
115 private static void selectJsonRow(Session session) {
116
117 // Reading the whole row as a JSON object
118 Statement stmt = select().json()
119 .from("examples", "json_jackson_row")
120 .where(in("id", 1, 2));
121
122 ResultSet rows = session.execute(stmt);
123
124 for (Row row : rows) {
125 // SELECT JSON returns only one column for each row, of type VARCHAR,
126 // containing the row as a JSON payload
127 User user = row.get(0, User.class);
128 System.out.printf("Retrieved user: %s%n", user);
129 }
130 }
131
132 @SuppressWarnings("unused")
133 public static class User {
134
135 private final int id;
136
137 private final String name;
138
139 private final int age;
140
141 @JsonCreator
142 public User(@JsonProperty("id") int id, @JsonProperty("name") String name, @JsonProperty("age") int age) {
143 this.id = id;
144 this.name = name;
145 this.age = age;
146 }
147
148 public int getId() {
149 return id;
150 }
151
152 public String getName() {
153 return name;
154 }
155
156 public int getAge() {
157 return age;
158 }
159
160 @Override
161 public String toString() {
162 return String.format("%s (id %d, age %d)", name, id, age);
163 }
164 }
165}