Elffuss BraidHub

kikocis/java-driver public

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