Elffuss BraidHub

kikocis/java-driver public

65e685d3eeef · 10.5 KiBRenderedRawPermalink
1## Prepared statements
2
3Use [PreparedStatement] for queries that are executed multiple times in your application:
4
5```java
6PreparedStatement prepared = session.prepare(
7 "insert into product (sku, description) values (?, ?)");
8
9BoundStatement bound = prepared.bind("234827", "Mouse");
10session.execute(bound);
11
12session.execute(prepared.bind("987274", "Keyboard"));
13```
14
15When you prepare the statement, Cassandra will parse the query string, cache the result and return a unique identifier
16(the `PreparedStatement` object keeps an internal reference to that identifier):
17
18```ditaa
19client driver Cassandra
20--+------------------------+----------------+------
21 | | |
22 | session.prepare(query) | |
23 |----------------------->| |
24 | | PREPARE(query) |
25 | |--------------->|
26 | | |
27 | | |
28 | | | - compute id
29 | | | - parse query string
30 | | | - cache (id, parsed)
31 | | |
32 | | PREPARED(id) |
33 | |<---------------|
34 | PreparedStatement(id) | |
35 |<-----------------------| |
36```
37
38When you bind and execute a prepared statement, the driver will only send the identifier, which allows Cassandra to
39skip the parsing phase:
40
41```ditaa
42client driver Cassandra
43--+---------------------------------+---------------------+------
44 | | |
45 | session.execute(BoundStatement) | |
46 |-------------------------------->| |
47 | | EXECUTE(id, values) |
48 | |-------------------->|
49 | | |
50 | | |
51 | | | - get cache(id)
52 | | | - execute query
53 | | |
54 | | ROWS |
55 | |<--------------------|
56 | | |
57 |<--------------------------------| |
58```
59
60
61You should prepare only once, and cache the `PreparedStatement` in your application (it is thread-safe). If you call
62`prepare` multiple times with the same query string, the driver will log a warning.
63
64If you execute a query only once, a prepared statement is inefficient because it requires two roundtrips. Consider a
65[simple statement](../simple/) instead.
66
67### Parameters and binding
68
69Parameters can be either anonymous or named (named parameters are only
70available with [native protocol](../../native_protocol) v2 or above):
71
72```java
73ps1 = session.prepare("insert into product (sku, description) values (?, ?)");
74ps2 = session.prepare("insert into product (sku, description) values (:s, :d)");
75```
76
77To turn the statement into its executable form, you need to *bind* it to create a [BoundStatement]. As shown previously,
78there is a shorthand to provide the parameters in the same call:
79
80```java
81BoundStatement bound = ps1.bind("324378", "LCD screen");
82```
83
84You can also bind first, then use setters, which is slightly more
85explicit:
86
87```java
88// Positional setters:
89BoundStatement bound = ps1.bind()
90 .setString(0, "324378")
91 .setString(1, "LCD screen");
92
93// Named setters:
94BoundStatement bound = ps2.bind()
95 .setString("s", "324378")
96 .setString("d", "LCD screen");
97```
98
99You must set all parameters. If you fail to do so, the driver will throw an error when executing the statement. If you
100want to send a `NULL` value, set it explicitly to `null` (use `setToNull` for Java primitives). Note that this is a new
101behavior in 2.1, branch 2.0 of the driver assumed unset values were null.
102
103You can use named setters even if the query uses anonymous parameters;
104Cassandra will name the parameters after the column they apply to:
105
106```java
107BoundStatement bound = ps1.bind()
108 .setString("sku", "324378")
109 .setString("description", "LCD screen");
110```
111
112This can be ambiguous if the query uses the same column multiple times,
113for example: `select * from sales where sku = ? and date > ? and date <
114?`. In these situations, use positional setters or named parameters.
115
116A bound statement also has getters to retrieve the values. Note that
117this has a small performance overhead since values are stored in their
118serialized form.
119
120`BoundStatement` is **not thread-safe**. You can reuse an instance multiple times with different parameters, but only
121from a single thread, and only if you use the synchronous API ([Session#execute][execute] is fine,
122[Session#executeAsync][executeAsync] is not).
123Also, make sure you don't accidentally reuse parameters from previous executions.
124
125### Preparing on multiple nodes
126
127Cassandra does not replicate prepared statements across the cluster. It is the
128driver's responsibility to ensure that each node's cache is up to
129date. It uses a number of strategies to achieve this:
130
1311. When a statement is initially prepared, it is first sent to a single
132 node in the cluster (this avoids hitting all nodes in case
133 the query string is wrong). Once that node replies successfully, the
134 driver re-prepares on all remaining nodes:
135
136 ```ditaa
137 client driver node1 node2 node3
138 --+------------------------+----------------+--------------+------+---
139 | | | | |
140 | session.prepare(query) | | | |
141 |----------------------->| | | |
142 | | PREPARE(query) | | |
143 | |--------------->| | |
144 | | | | |
145 | | PREPARED(id) | | |
146 | |<---------------| | |
147 | | | | |
148 | | | | |
149 | | PREPARE(query) | |
150 | |------------------------------>| |
151 | | | | |
152 | | PREPARE(query) | |
153 | |------------------------------------->|
154 | | | | |
155 |<-----------------------| | | |
156 ```
157
158 The prepared statement identifier is deterministic (it's a hash of the query string), so it is the same
159 for all nodes.
160
1612. if a node crashes, it loses all of its prepared statements. So the
162 driver keeps a client-side cache; anytime a node is marked back up,
163 the driver re-prepares all statements on it;
164
1653. finally, if the driver tries to execute a statement and finds out
166 that the coordinator doesn't know about it, it will re-prepare the
167 statement on the fly (this is transparent for the client, but will cost
168 two extra roundtrips):
169
170 ```ditaa
171 client driver node1
172 --+-------------------------------+------------------------------+--
173 | | |
174 |session.execute(boundStatement)| |
175 +------------------------------>| |
176 | | EXECUTE(id, values) |
177 | |----------------------------->|
178 | | |
179 | | UNPREPARED |
180 | |<-----------------------------|
181 | | |
182 | | |
183 | | PREPARE(query) |
184 | |----------------------------->|
185 | | |
186 | | PREPARED(id) |
187 | |<-----------------------------|
188 | | |
189 | | |
190 | | EXECUTE(id, values) |
191 | |----------------------------->|
192 | | |
193 | | ROWS |
194 | |<-----------------------------|
195 | | |
196 |<------------------------------| |
197 ```
198
199You can customize these strategies through `QueryOptions`:
200
201* [setPrepareOnAllHosts] controls whether statements are initially
202 re-prepared on other hosts (step 1 above);
203* [setReprepareOnUp] controls whether statements are re-prepared on a
204 node that comes back up (step 2 above).
205
206Changing the driver's defaults should be done with care and only in
207specific situations; read each method's Javadoc for detailed
208explanations.
209
210[PreparedStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PreparedStatement.html
211[BoundStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BoundStatement.html
212[setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts-boolean-
213[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp-boolean-
214[execute]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#execute-com.datastax.driver.core.Statement-
215[executeAsync]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement-