Elffuss BraidHub

kikocis/java-driver public

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