-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathsqlquery.html
More file actions
278 lines (237 loc) · 8.55 KB
/
sqlquery.html
File metadata and controls
278 lines (237 loc) · 8.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
<html>
<head>
<title>SqlQuery | Ebean</title>
<meta name="layout" content="_layout2/base-docs.html"/>
<meta name="bread1" content="Query" href="/docs/query/"/>
<meta name="bread2" content="SqlQuery" href="/docs/query/sqlquery"/>
<#assign n0_docs="true">
<#assign n1_query="true">
<#assign sqlquery= "true">
</head>
<body>
<h2>SqlQuery</h2>
<p>
With SqlQuery we can execute sql queries without any entity beans or dto beans.
Instead we can:
</p>
<ul>
<li>Read JDBC <code>ResultSet</code> directly</li>
<li>Read as <code>SqlRow</code> objects</li>
<li>Use <code>mapToScalar()</code> and read simple scalar values like Long, BigDecimal, OffsetDateTime etc</li>
<li>use <code>mapTo()</code> and <code>RowMapper</code> to map and read objects</li>
</ul>
<p> </p>
<h5>Example findOne with SqlRow</h5>
<pre content="java">
String sql = "select id, name, when_active from customer where id = :id"
SqlRow row = DB.sqlQuery(sql)
.setParameter("id", 42)
.findOne();
String name = row.getString("name");
Timestamp active = row.getTimestamp("when_active");
</pre>
<p> </p>
<h5>Example findEachRow with ResultSet</h5>
<pre content="java">
String sql = "select id, name, status from customer order by name desc";
DB.sqlQuery(sql)
.findEachRow((resultSet, rowNum) -> {
long id = resultSet.getLong(1);
String name = resultSet.getString(2);
...
});
</pre>
<h5>Example mapToScalar()</h5>
<pre content="java">
String sql = "select mysequence.nextval";
Long nextVal = DB.sqlQuery(sql)
.mapToScalar(Long.class)
.findOne();
</pre>
<h2 id="bind-positioned" class="art">Binding positioned parameters using ?</h2>
<p>
Positioned parameters use <code>?</code> as the placeholder.
</p>
<pre content="java">
String sql = "select id, name, when_active from customer where status = ? and when_created > ?";
List<|SqlRow> rows = DB.sqlQuery(sql)
.setParameter(1, "NEW")
.setParameter(2, lastWeek)
.findList();
</pre>
<p>
We can omit the index positions like the next example.
</p>
<pre content="java">
String sql = "select id, name, when_active from customer where status = ? and when_created > ?";
List<|SqlRow> rows = DB.sqlQuery(sql)
.setParameter("NEW")
.setParameter(lastWeek)
.findList();
</pre>
<p>
We can alternatively set multiple positioned parameters using <code>setParameters()</code>.
</p>
<pre content="java">
String sql = "select id, name, when_active from customer where status = ? and when_created > ?";
List<|SqlRow> rows = DB.sqlQuery(sql)
.setParameters("NEW", lastWeek)
.findList();
</pre>
<h2 id="bind-named" class="art">Binding named parameters using :name</h2>
<p>
Named parameters use the form <code>:foo</code> as the placeholder. Named parameters have the
advantages that we can use them to bind collections into an <code>IN</code> expression and
that the same parameter can appear multiple times in the SQL.
</p>
<h5>Binding using named parameters</h5>
<pre content="java">
String sql =
"select id, name, when_active " +
"from customer " +
"where status = :status and when_created > :created";
List<|SqlRow> rows = DB.sqlQuery(sql)
.setParameter("status", "NEW")
.setParameter("created", lastWeek)
.findList();
</pre>
<h2 id="collections" class="art">Binding collections</h2>
<p>
To bind collections of values into an IN clause we need to used named parameters
or indexed positioned parameters.
</p>
<h5>Named parameter example (:names)</h5>
<pre content="java">
String sql = "select c.id, c.name from customer c where c.name in (:names)";
List<|SqlRow> rows = DB.sqlQuery(sql)
.setParameter("names", asList("Rob", "Fiona", "Jack"))
.findList();
</pre>
<h5>Index parameter example - ?2</h5>
<pre content="java">
String sql = "select c.id, c.name from customer c " +
"where c.status = ? and c.name in (?2) and c.when_created > ?";
List<|SqlRow> rows = DB.sqlQuery(sql)
.setParameter("NEW")
.setParameter(asList("Rob", "Fiona", "Jack"))
.setParameter(lastWeek)
.findList();
</pre>
<h2 id="any" class="art">Postgres ANY</h2>
<p>
When using Postgres we can use Postgres <code>ANY</code> in SqlQuery with positioned parameters.
</p>
<p>
The benefit of using Postgres <code>ANY</code> is that we end up using a single SQL query regardless of the number
of parameters - a single JDBC PreparedStatement and the database has a single SQL query to parse. This results in
the database doing less hard parsing and better use of PreparedStatement cache, less query plans to cache, less memory consumed.
</p>
<h5>Example</h5>
<p>
When using index positioned parameters and binding a collection that will bind as a JDBC ARRAY.
</p>
<pre content="java">
List<|Integer> ids = List.of(1, 2);
List<|SqlRow> list = DB.sqlQuery("select id, name from o_customer where id = any(?)")
.setParameter(1, ids) // bind as JDBC ARRAY
.findList();
</pre>
<p>
When using Postgres we would often prefer to use that over using an <code>IN</code> clause
like the example below. The reason we prefer <code>ANY</code> is that it does not matter how
many elements we have in the ARRAY we end up with a single SQL statement. This gives us a single
query plan, single PrepareStatement and on the database end a single query statement to parse regardless
of the number of id values we are binding.
</p>
<p>
In comparison to using an <code>IN</code> clause, if we have 3 ids that is a different SQL query to one
that has 4 ids for example - we end up with more distinct PreparedStatements, potentially a lot more depending
on the number of id values we have.
</p>
<pre content="java">
List<|SqlRow> list = DB.sqlQuery("select id, name from o_customer where id in (:idList)")
.setParameter("idList", ids) // bind parameter expansion
.findList();
</pre>
<p>
Using the <code>IN</code> clause will result in a different SQL query when we have different numbers of
id values. With 4 id values supplied then <code>in (:idList)</code> is turned into SQL <code>in (?, ?, ?, ?)</code>.
</p>
<h2 id="limit" class="art">firstRow / maxRows</h2>
<p>
We can specify <em>firstRow</em> and <em>maxRows</em> on a SqlQuery and Ebean will modify
the SQL based on the database platform to add the appropriate row limit clause.
</p>
<pre content="java">
String sql = "select id, name, when_active from customer where status = ?";
List<|SqlRow> rows = DB.sqlQuery(sql)
.setParameter(1, "NEW")
.setFirstRow(10)
.setMaxRows(10)
.findList();
</pre>
<h2 id="scalar" class="art">mapToScalar() - single column scalar result</h2>
<p>
Use <code>mapToScalar()</code> when the query has a single column in the <em>select clause</em>.
This specifies the type to use to read the result.
</p>
<pre content="java">
String sql = "select mysequence.nextval";
Long nextVal = DB.sqlQuery(sql)
.mapToScalar(Long.class)
.findOne();
</pre>
<pre content="java">
String sql = "select max(unit_price) from order_lines where order_qty > ?";
BigDecimal maxPrice = DB.sqlQuery(sql)
.setParameter(42)
.mapToScalar(BigDecimal.class)
.findOne();
</pre>
<pre content="java">
String sql = "select max(order_date) from orders where customer_id = ?";
OffsetDateTime maxDate = DB.sqlQuery(sql)
.setParameter(42)
.mapToScalar(OffsetDateTime.class)
.findOne();
</pre>
<p>
All scalar types that Ebean supports can be used - refer to <a href="/docs/mapping/type/">mapping types</a>.
</p>
<h2 id="rowmapper" class="art">mapTo() - RowMapper</h2>
<p>
We can implement a <em>RowMapper</em> to convert a ResultSet into a dto bean.
</p>
<p>
Note that this similar to <a href="dtoquery">DtoQuery</a> except that the mapping is here is explicit
and with DtoQuery the mapping is effectively automatic (no effort) based on naming convention mapping.
In that sense the expectation is that people will use DtoQuery first and only use this explicit
RowMapping when necessary.
</p>
<pre content="java">
static class CustomerDtoMapper implements RowMapper<|CustomerDto> {
@Override
public CustomerDto map(ResultSet resultSet, int rowNum) throws SQLException {
long id = resultSet.getLong(1);
String name = resultSet.getString(2);
String status = resultSet.getString(3);
return new CustomerDto(id, name, status);
}
}
...
static final CustomerDtoMapper CUSTOMER_MAPPER = new CustomerDtoMapper()
</pre>
<p> </p>
<p>
Then we can use it to return DTO beans.
</p>
<pre content="java">
String sql = "select id, name, status from customer where name = ?";
List<|CustomerDto> rob = DB.sqlQuery(sql)
.setParameter("Rob")
.mapTo(CUSTOMER_MAPPER)
.findList();
</pre>
<@next_edit "SqlUpdate" "/docs/query/sqlupdate" "/docs/query/sqlquery.html"/>
</body>
</html>