forked from spring-projects/spring-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjdbc.xml
2969 lines (2449 loc) · 142 KB
/
jdbc.xml
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="UTF-8"?>
<chapter xml:id="jdbc"
xmlns="http://docbook.org/ns/docbook" version="5.0"
xmlns:xl="http://www.w3.org/1999/xlink"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd
http://www.w3.org/1999/xlink http://www.docbook.org/xml/5.0/xsd/xlink.xsd">
<title>Data access with JDBC</title>
<section xml:id="jdbc-introduction">
<title>Introduction to Spring Framework JDBC</title>
<para>The value-add provided by the Spring Framework JDBC abstraction is
perhaps best shown by the sequence of actions outlined in the table below.
The table shows what actions Spring will take care of and which actions
are the responsibility of you, the application developer.<!--Is this sequence correct, as far as what developer does and doesn't do? Does it adhere to info in the rest of the chapter?
--><!--How does JDBC know what connection parameters are if a human does not at some point define them?--><!--TR: OK. I have rewritten this as a table indicating who has what responsibility. --></para>
<table align="left" width="">
<title>Spring JDBC - who does what?</title>
<tgroup cols="3">
<colspec colnum="1" colwidth="350" />
<colspec colnum="2" colwidth="40" />
<colspec colnum="3" colwidth="40" />
<thead>
<row>
<entry align="center">Action</entry>
<entry align="center">Spring</entry>
<entry align="center">You</entry>
</row>
</thead>
<tbody>
<row>
<entry>Define connection parameters.</entry>
<entry align="center"><emphasis role="bold"></emphasis></entry>
<entry align="center">X</entry>
</row>
<row>
<entry>Open the connection.</entry>
<entry align="center">X</entry>
<entry align="center"></entry>
</row>
<row>
<entry>Specify the SQL statement.</entry>
<entry align="center"></entry>
<entry align="center">X</entry>
</row>
<row>
<entry>Declare parameters and provide parameter values</entry>
<entry align="center"></entry>
<entry align="center">X</entry>
</row>
<row>
<entry>Prepare and execute the statement.</entry>
<entry align="center">X</entry>
<entry align="center"></entry>
</row>
<row>
<entry>Set up the loop to iterate through the results (if
any).</entry>
<entry align="center">X</entry>
<entry align="center"></entry>
</row>
<row>
<entry>Do the work for each iteration.</entry>
<entry align="center"></entry>
<entry align="center">X</entry>
</row>
<row>
<entry>Process any exception.</entry>
<entry align="center">X</entry>
<entry align="center"></entry>
</row>
<row>
<entry>Handle transactions.</entry>
<entry align="center">X</entry>
<entry align="center"></entry>
</row>
<row>
<entry>Close the connection, statement and resultset.</entry>
<entry align="center">X</entry>
<entry align="center"></entry>
</row>
</tbody>
</tgroup>
</table>
<para>The Spring Framework takes care of all the low-level details that
can make JDBC such a tedious API to develop with.</para>
<section xml:id="jdbc-choose-style">
<title>Choosing an approach for JDBC database access</title>
<para>You can choose among several approaches to form the basis for your
JDBC database access. In addition to three flavors of the JdbcTemplate,
a new SimpleJdbcInsert and SimplejdbcCall approach optimizes database
metadata, and the RDBMS Object style takes a more object-oriented
approach similar to that of JDO Query design. Once you start using one
of these approaches, you can still mix and match to include a feature
from a different approach. All approaches require a JDBC 2.0-compliant
driver, and some advanced features require a JDBC 3.0 driver.</para>
<note>
<para>Spring 3.0 updates all of the following approaches with Java 5
support such as generics and varargs.<!--Is there a formal name for varargs? Is this written correctly?I've inserted this note to avoid redundancy below.--></para>
</note>
<itemizedlist>
<listitem>
<para><emphasis role="bold">JdbcTemplate</emphasis> is the classic
Spring JDBC approach and the most popular. This "lowest level"
approach and all others use a JdbcTemplate under the covers, and all
are updated with Java 5 support such as generics and varargs.</para>
</listitem>
<listitem>
<para><emphasis role="bold">NamedParameterJdbcTemplate</emphasis>
wraps a <code>JdbcTemplate</code> to provide named parameters
instead of the traditional JDBC "?" placeholders. This approach
provides better documentation and ease of use when you have multiple
parameters for an SQL statement.</para>
</listitem>
<listitem>
<para><emphasis role="bold">SimpleJdbcInsert and
SimpleJdbcCall</emphasis> optimize database metadata to limit the
amount of necessary configuration. This approach simplifies coding
so that you only need to provide the name of the table or procedure
and provide a map of parameters matching the column names.
This only works if the database provides adequate metadata. If the
database doesn't provide this metadata, you will have to provide
explicit configuration of the parameters.</para>
</listitem>
<listitem>
<para><emphasis role="bold">RDBMS Objects including MappingSqlQuery,
SqlUpdate and StoredProcedure</emphasis> requires you to create
reusable and thread-safe objects during initialization of your data
access layer. This approach is modeled after JDO Query wherein you
define your query string, declare parameters, and compile the query.
Once you do that, execute methods can be called multiple times with
various parameter values passed in.</para>
</listitem>
</itemizedlist>
</section>
<section xml:id="jdbc-packages">
<title>Package hierarchy<!--I have provided links to main sections that deal with most packages. TR: OK--></title>
<para>The Spring Framework's JDBC abstraction framework consists of four
different packages, namely <literal>core</literal>,
<literal>datasource</literal>, <literal>object</literal>, and
<literal>support</literal>.</para>
<para>The <literal>org.springframework.jdbc.core</literal> package
contains the <classname>JdbcTemplate</classname> class and its various
callback interfaces, plus a variety of related classes. A subpackage
named <literal>org.springframework.jdbc.core.simple</literal> contains
the <classname>SimpleJdbcInsert</classname> and
<classname>SimpleJdbcCall</classname> classes. Another subpackage named
<literal>org.springframework.jdbc.core.namedparam</literal> contains the
<classname>NamedParameterJdbcTemplate</classname> class and the related
support classes. See <xref linkend="jdbc-core" />, <xref
linkend="jdbc-advanced-jdbc" />, and <xref
linkend="jdbc-simple-jdbc" /></para>
<para>The <literal>org.springframework.jdbc.datasource</literal> package
contains a utility class for easy
<interfacename>DataSource</interfacename> access, and various simple
<interfacename>DataSource</interfacename> implementations that can be
used for testing and running unmodified JDBC code outside of a Java EE
container. A subpackage named
<literal>org.springfamework.jdbc.datasource.embedded</literal> provides
support for creating in-memory database instances using Java database
engines such as HSQL and H2. See <xref linkend="jdbc-connections" /> and
<xref linkend="jdbc-embedded-database-support" /></para>
<para>The <literal>org.springframework.jdbc.object</literal> package
contains classes that represent RDBMS queries, updates, and stored
procedures as thread safe, reusable objects. See <xref
linkend="jdbc-object" />.This approach is modeled by JDO, although of
course objects returned by queries are <quote>disconnected</quote> from
the database. This higher level of JDBC abstraction depends on the
lower-level abstraction in the
<literal>org.springframework.jdbc.core</literal> package.</para>
<para><!--Need x-ref for preceding and next sentences. TR: Revised, please review. Combined to single paragraph about exception translation.-->The
<literal>org.springframework.jdbc.support</literal> package provides
<classname>SQLException</classname> translation functionality and some
utility classes. Exceptions thrown during JDBC processing are translated
to exceptions defined in the <literal>org.springframework.dao</literal>
package. This means that code using the Spring JDBC abstraction layer
does not need to implement JDBC or RDBMS-specific error handling. All
translated exceptions are unchecked, which gives you the option of
catching the exceptions from which you can recover while allowing other
exceptions to be propagated to the caller. See <xref
linkend="jdbc-SQLExceptionTranslator" />.</para>
</section>
</section>
<section xml:id="jdbc-core">
<title>Using the JDBC core classes to control basic JDBC processing and
error handling<!--Note: I moved the *DataSource* subsection out of this section because it seems to belong more under *Controlling database connections.*--><!--This section here is about core classes, but datasource is a separate package from core. See *Package hierarchy* section above. TR: OK--></title>
<section xml:id="jdbc-JdbcTemplate">
<title><classname>JdbcTemplate</classname></title>
<para>The <classname>JdbcTemplate</classname> class is the central class
in the JDBC core package. It handles the creation and release of
resources, which helps you avoid common errors such as forgetting to
close the connection. It performs the basic tasks of the core JDBC
workflow such as statement creation and execution, leaving application
code to provide SQL and extract results. The
<classname>JdbcTemplate</classname> class executes SQL queries, update
statements and stored procedure calls, performs iteration over
<interfacename>ResultSet</interfacename>s and extraction of returned
parameter values.<!--The wording of the preceding sentence does not track. Which is correct: the class *executes* queries, *updated* statements, --><!--and stored procedure calls...OR the class *executes* queries and *updates* statements and stored procedure calls. Second part of--><!--sentence; is this clear? It *imitates* iteration and extraction? TR: Revised, please review. The class executes *SQL queries*, *update statements* or *stored procedure calls* ...-->
It also catches JDBC exceptions and translates them to the generic, more
informative, exception hierarchy defined in the
<literal>org.springframework.dao</literal> package.</para>
<para>When you use the <classname>JdbcTemplate</classname> for your
code, you only need to implement callback interfaces, giving them a
clearly defined contract. The
<interfacename>PreparedStatementCreator</interfacename> callback
interface creates a prepared statement given a
<interfacename>Connection</interfacename> provided by this class,
providing SQL and any necessary parameters. The same is true for the
<interfacename>CallableStatementCreator</interfacename> interface, which
creates callable statements. The
<interfacename>RowCallbackHandler</interfacename> interface extracts
values from each row of a
<interfacename>ResultSet</interfacename>.</para>
<!--and stored procedure calls? TR: they are handled by the CallableStatement; Queries and update statements are handled by PreparedStatement.-->
<para>The <classname>JdbcTemplate</classname> can be used within a DAO
implementation through direct instantiation with a
<interfacename>DataSource</interfacename> reference, or be configured in
a Spring IoC container and given to DAOs as a bean reference. <note>
<para>The <interfacename>DataSource</interfacename> should always be
configured as a bean in the Spring IoC container. In the first case
the bean is given to the service directly; in the second case it is
given to the prepared template.<!--I've revised so that it reads better, but please clarify second sentence: Specify what *the first case* is, what--><!--do you mean by *is given* and it's given to *which* service? First mention of a service. Specify what *second--><!-- case* is and what you mean by *is given*. TR: OK.--></para>
</note></para>
<para>All SQL issued by this class is logged at the
<literal>DEBUG</literal> level under the category corresponding to the
fully qualified class name of the template instance (typically
<classname>JdbcTemplate</classname>, but it may be different if you are
using a custom subclass of the <classname>JdbcTemplate</classname>
class).</para>
<section xml:id="jdbc-JdbcTemplate-examples">
<title>Examples of JdbcTemplate class usage</title>
<para>This section provides some examples of
<classname>JdbcTemplate</classname> class usage. These examples are
not an exhaustive list of all of the functionality exposed by the
<classname>JdbcTemplate</classname>; see the attendant Javadocs for
that.</para>
<section xml:id="jdbc-JdbcTemplate-examples-query">
<title>Querying (SELECT)</title>
<para>Here is a simple query for getting the number of rows in a
relation:</para>
<programlisting language="java">int rowCount = this.jdbcTemplate.queryForInt("select count(*) from t_actor");</programlisting>
<para>A simple query using a bind variable:</para>
<programlisting language="java">int countOfActorsNamedJoe = this.jdbcTemplate.queryForInt(
"select count(*) from t_actor where first_name = ?", "Joe");</programlisting>
<para>Querying for a <classname>String</classname>:</para>
<programlisting language="java">String lastName = this.jdbcTemplate.queryForObject(
"select last_name from t_actor where id = ?",
new Object[]{1212L}, String.class);</programlisting>
<para>Querying and populating a <emphasis>single</emphasis> domain
object:</para>
<programlisting language="java">Actor actor = this.jdbcTemplate.queryForObject(
"select first_name, last_name from t_actor where id = ?",
new Object[]{1212L},
new RowMapper<Actor>() {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
});
</programlisting>
<para>Querying and populating a number of domain objects:</para>
<programlisting language="java">List<Actor> actors = this.jdbcTemplate.query(
"select first_name, last_name from t_actor",
new RowMapper<Actor>() {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
});
</programlisting>
<para>If the last two snippets of code actually existed in the same
application, it would make sense to remove the duplication present
in the two <interfacename>RowMapper</interfacename> anonymous inner
classes, and extract them out into a single class (typically a
<literal>static</literal> inner class) that can then be referenced
by DAO methods as needed. For example, it may be better to write the
last code snippet as follows:</para>
<programlisting language="java">public List<Actor> findAllActors() {
return this.jdbcTemplate.query( "select first_name, last_name from t_actor", new ActorMapper());
}
private static final class ActorMapper implements RowMapper<Actor> {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
}</programlisting>
</section>
<section xml:id="jdbc-JdbcTemplate-examples-update">
<title>Updating (INSERT/UPDATE/DELETE) with jdbcTemplate<!--Provide introductory text as with other examples. TR: OK.--></title>
<para>You use the <methodname>update(..)</methodname> method to
perform insert, update and delete operations. Parameter values are
usually provided as var args or alternatively as an object
array.</para>
<programlisting language="java">this.jdbcTemplate.update(
"insert into t_actor (first_name, last_name) values (?, ?)",
"Leonor", "Watling");</programlisting>
<programlisting language="java">this.jdbcTemplate.update(
"update t_actor set = ? where id = ?",
"Banjo", 5276L);</programlisting>
<programlisting language="java">this.jdbcTemplate.update(
"delete from actor where id = ?",
Long.valueOf(actorId));</programlisting>
</section>
<section xml:id="jdbc-JdbcTemplate-examples-other">
<title>Other jdbcTemplate operations</title>
<para>You can use the <methodname>execute(..)</methodname> method to
execute any arbitrary SQL, and as such the method is often used for
DDL statements. It is heavily overloaded with variants taking
callback interfaces, binding variable arrays, and so on.</para>
<programlisting language="java">this.jdbcTemplate.execute("create table mytable (id integer, name varchar(100))");</programlisting>
<para>The following example invokes a simple stored procedure. More
sophisticated stored procedure support is <link
linkend="jdbc-StoredProcedure">covered later</link>.</para>
<programlisting language="java">this.jdbcTemplate.update(
"call SUPPORT.REFRESH_ACTORS_SUMMARY(?)",
Long.valueOf(unionId));</programlisting>
</section>
</section>
<section xml:id="jdbc-JdbcTemplate-idioms">
<title><classname>JdbcTemplate</classname> best practices</title>
<para>Instances of the <classname>JdbcTemplate</classname> class are
<emphasis>threadsafe once configured</emphasis>. This is important
because it means that you can configure a single instance of a
<classname>JdbcTemplate</classname> and then safely inject this
<emphasis>shared</emphasis> reference into multiple DAOs (or
repositories). The <classname>JdbcTemplate</classname> is stateful, in
that it maintains a reference to a
<interfacename>DataSource</interfacename>, but this state is
<emphasis>not</emphasis> conversational state.</para>
<para>A common practice when using the
<classname>JdbcTemplate</classname> class (and the associated <link
linkend="jdbc-NamedParameterJdbcTemplate"><classname>NamedParameterJdbcTemplate</classname></link>
classes) is to configure a <interfacename>DataSource</interfacename>
in your Spring configuration file, and then dependency-inject that
shared <interfacename>DataSource</interfacename> bean into your DAO
classes; the <classname>JdbcTemplate</classname> is created in the
setter for the <interfacename>DataSource</interfacename>. This leads
to DAOs that look in part like the following:</para>
<programlisting language="java">public class JdbcCorporateEventDao implements CorporateEventDao {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
<emphasis role="bold">this.jdbcTemplate = new JdbcTemplate(dataSource);</emphasis>
}
<lineannotation>// JDBC-backed implementations of the methods on the CorporateEventDao follow...</lineannotation>
}</programlisting>
<para>The corresponding configuration might look like this.</para>
<programlisting language="xml"><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="corporateEventDao" class="com.example.JdbcCorporateEventDao">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<context:property-placeholder location="jdbc.properties"/>
</beans></programlisting>
<para>An alternative to explicit configuration is to use
component-scanning and annotation support for dependency injection. In
this case you annotate the class with
<interfacename>@Repository</interfacename> (which makes it a candidate
for component-scanning) and annotate the
<classname>DataSource</classname> setter method with
<interfacename>@Autowired</interfacename>.<!--Re preceding sentence, I don't see @Autowired in next two examples. TR: OK AS IS. Made it *bold*--></para>
<para><programlisting language="java"><emphasis role="bold">@Repository</emphasis>
public class JdbcCorporateEventDao implements CorporateEventDao {
private JdbcTemplate jdbcTemplate;
<emphasis role="bold">@Autowired</emphasis>
public void setDataSource(DataSource dataSource) {
<emphasis role="bold">this.jdbcTemplate = new JdbcTemplate(dataSource);</emphasis>
}
<lineannotation>// JDBC-backed implementations of the methods on the CorporateEventDao follow...</lineannotation>
}</programlisting></para>
<para>The corresponding XML configuration file <!--*corresponding* to what? TR: to the prvious code-snippet-->would
look like the following:</para>
<para><programlisting language="xml"><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Scans within the base package of the application for @Components to configure as beans -->
<context:component-scan base-package="org.springframework.docs.test" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<context:property-placeholder location="jdbc.properties"/>
</beans></programlisting>If you are using Spring's
<classname>JdbcDaoSupport</classname> class, and your various
JDBC-backed DAO classes extend from it, then your sub-class inherits a
<methodname>setDataSource(..)</methodname> method from the
<classname>JdbcDaoSupport</classname> class. <!--Revise to clarify what you mean by inheriting method *for free*. For free as opposed to what? Also you don't inherit, don't your--><!--subclasses inherit? TR: Revised, please review.-->You
can choose whether to inherit from this class. The
<classname>JdbcDaoSupport</classname> class is provided as a
convenience only.</para>
<para>Regardless of which of the above template initialization styles
you choose to use (or not), it is seldom necessary to create a new
instance of a <classname>JdbcTemplate</classname> class each time you
want to execute SQL. Once configured, a
<classname>JdbcTemplate</classname> instance is threadsafe. You may
want multiple <classname>JdbcTemplate</classname> instances if your
application accesses multiple databases, which requires multiple
<interfacename>DataSources</interfacename>, and subsequently multiple
differently configured <classname>JdbcTemplates</classname>.</para>
</section>
</section>
<section xml:id="jdbc-NamedParameterJdbcTemplate">
<title><classname>NamedParameterJdbcTemplate</classname></title>
<para>The <classname>NamedParameterJdbcTemplate</classname> class adds
support for programming JDBC statements using named parameters, as
opposed to programming JDBC statements using only classic placeholder
(<literal>'?'</literal>) arguments. The
<classname>NamedParameterJdbcTemplate</classname> class wraps a
<classname>JdbcTemplate</classname>, and delegates to the wrapped
<classname>JdbcTemplate</classname> to do much of its work. This section
describes only those areas of the
<classname>NamedParameterJdbcTemplate</classname> class that differ from
the <classname>JdbcTemplate</classname> itself; namely, programming JDBC
statements using named parameters.</para>
<programlisting language="java"><lineannotation>// some JDBC-backed DAO class...</lineannotation>
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
public int countOfActorsByFirstName(String firstName) {
String sql = "select count(*) from T_ACTOR where first_name = :first_name";
SqlParameterSource namedParameters = new MapSqlParameterSource("first_name", firstName);
return namedParameterJdbcTemplate.queryForInt(sql, namedParameters);
}</programlisting>
<para>Notice the use of the named parameter notation in the value
assigned to the <literal>sql</literal> variable, and the corresponding
value that is plugged into the <literal>namedParameters</literal>
variable (of type <classname>MapSqlParameterSource</classname>).</para>
<para>Alternatively, you can pass along named parameters and their
corresponding values to a
<classname>NamedParameterJdbcTemplate</classname> instance by using the
<interfacename>Map</interfacename>-based style.<!--Revision ok? Clarify to say *Alternatively* you can pass along OR *In addition* you can pass along, to clarify whether you can do this--><!--instead of doing what sentence before it says to do, or in addition to doing it. This needs to be clear. TR: OK.-->The
remaining methods exposed by the
<interfacename>NamedParameterJdbcOperations</interfacename> and
implemented by the <classname>NamedParameterJdbcTemplate</classname>
class follow a similar pattern and are not covered here.</para>
<para>The following example shows the use of the
<interfacename>Map</interfacename>-based style.<!--Need an intro sentence to the following example. What does it show, what's its purpose? TR: OK.--></para>
<programlisting language="java"><lineannotation>// some JDBC-backed DAO class...</lineannotation>
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
public int countOfActorsByFirstName(String firstName) {
String sql = "select count(*) from T_ACTOR where first_name = :first_name";
Map namedParameters = Collections.singletonMap("first_name", firstName);
return this.namedParameterJdbcTemplate.queryForInt(sql, namedParameters);
}</programlisting>
<para>One nice feature related to the
<classname>NamedParameterJdbcTemplate</classname> (and existing in the
same Java package) is the <classname>SqlParameterSource</classname>
interface. You have already seen an example of an implementation of this
interface in one of the previous code snippet (the
<classname>MapSqlParameterSource</classname> class).
<!--Revision ok?Why say *another feature*? So far this is the only feature discussed for NamedParameterJDBC template. It's mentioned above.--><!--In next paragraph you do describe another implementation. --><!--TR: Revised, please review.-->
An <classname>SqlParameterSource</classname> is a source of
named parameter values to a
<classname>NamedParameterJdbcTemplate</classname>. The
<classname>MapSqlParameterSource</classname> class is a very simple
implementation that is simply an adapter around a
<interfacename>java.util.Map</interfacename>, where the keys are the
parameter names and the values are the parameter values.</para>
<para>Another <interfacename>SqlParameterSource</interfacename>
implementation is the
<classname>BeanPropertySqlParameterSource</classname> class. This class
wraps an arbitrary JavaBean (that is, an instance of a class that
adheres to <link
xl:href="http://java.sun.com/products/javabeans/docs/spec.html">the JavaBean
conventions</link>), and uses the properties of the wrapped JavaBean as
the source of named parameter values.</para>
<programlisting language="java">public class Actor {
private Long id;
private String firstName;
private String lastName;
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
public Long getId() {
return this.id;
}
<lineannotation>// setters omitted...</lineannotation>
}</programlisting>
<programlisting language="java"><lineannotation>// some JDBC-backed DAO class...</lineannotation>
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
public int countOfActors(Actor exampleActor) {
<lineannotation>// notice how the named parameters match the properties of the above 'Actor' class</lineannotation>
String sql =
"select count(*) from T_ACTOR where first_name = :firstName and last_name = :lastName";
SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(exampleActor);
return this.namedParameterJdbcTemplate.queryForInt(sql, namedParameters);
}</programlisting>
<para>Remember that the
<classname>NamedParameterJdbcTemplate</classname> class
<emphasis>wraps</emphasis> a classic <classname>JdbcTemplate</classname>
template; if you need access to the wrapped
<classname>JdbcTemplate</classname> instance to access functionality
only present in the <classname>JdbcTemplate</classname> class, you can
use the <methodname>getJdbcOperations()</methodname> method to access
the wrapped <classname>JdbcTemplate</classname> through the
<interfacename>JdbcOperations</interfacename> interface.</para>
<para>See also <xref linkend="jdbc-JdbcTemplate-idioms" /> for
guidelines on using the
<classname>NamedParameterJdbcTemplate</classname> class in the context
of an application.</para>
</section>
<section xml:id="jdbc-SQLExceptionTranslator">
<title><interfacename>SQLExceptionTranslator</interfacename></title>
<para><interfacename>SQLExceptionTranslator</interfacename> is an
interface to be implemented by classes that can translate between
<classname>SQLExceptions</classname> and Spring's own
<classname>org.springframework.dao.DataAccessException</classname>,
which is agnostic in regard to data access strategy. Implementations can
be generic (for example, using SQLState codes for JDBC) or proprietary
(for example, using Oracle error codes) for greater precision.</para>
<para><classname>SQLErrorCodeSQLExceptionTranslator</classname> is the
implementation of <interfacename>SQLExceptionTranslator</interfacename>
that is used by default. This implementation uses specific vendor codes.
It is more precise than the <literal>SQLState</literal> implementation.
The error code translations are based on codes held in a JavaBean type
class called <classname>SQLErrorCodes</classname>. This class is created
and populated by an <classname>SQLErrorCodesFactory</classname> which as
the name suggests is a factory for creating
<classname>SQLErrorCodes</classname> based on the contents of a
configuration file named <filename
class="libraryfile">sql-error-codes.xml</filename>. This file is
populated with vendor codes and based on the
<code>DatabaseProductName</code> taken from the
<interfacename>DatabaseMetaData</interfacename>. The codes for the actual
database you are using are used.<!--what do you mean by *the current* database? --><!--TR: Revised, please review.--></para>
<para>The <classname>SQLErrorCodeSQLExceptionTranslator</classname>
applies matching rules in the following sequence: <!--This reflects sequence in which rules are applied, right? I revised to a numbered list.--><orderedlist
spacing="compact">
<note>
<para>The <classname>SQLErrorCodesFactory</classname> is used by
default to define Error codes and custom exception translations.
They are looked up in a file named
<filename>sql-error-codes.xml</filename> from the classpath and
the matching <classname>SQLErrorCodes</classname> instance is
located based on the database name from the database metadata of
the database in use.</para>
</note>
<listitem>
<para>Any custom translation implemented by a subclass. Normally
the provided concrete
<classname>SQLErrorCodeSQLExceptionTranslator</classname> is used
so this rule does not apply. It only applies if you have actually
provided a subclass implementation.<!--Pls revise last sentence to clarify. *Which* class is concrete? Why do you first refer to a subclass, then say *this class* is--><!--typically used and thus rule does not apply? This is really confusing.--><!--TR: Revised, please review.--></para>
</listitem>
<listitem>
<para>Any custom implementation of the
<classname>SQLExceptionTranslator</classname> interface that is
provided as the
<classname>customSqlExceptionTranslator</classname> property of
the <classname>SQLErrorCodes</classname> class.</para>
</listitem>
<listitem>
<para>The list of instances of the
<classname>CustomSQLErrorCodesTranslation</classname> class,
provided for the <classname>customTranslations</classname>
property of the <classname>SQLErrorCodes</classname> class, are
searched for a match.</para>
</listitem>
<listitem>
<para>Error code matching is applied.<!--Wording of the next sentence does not track. Please revise. --><!--TR: Revised, please review.--></para>
</listitem>
<listitem>
<para>Use the fallback translator.
<classname>SQLExceptionSubclassTranslator</classname> is the
default fallback translator. If this translation is not available
then the next fallback translator is the
<classname>SQLStateSQLExceptionTranslator</classname>.</para>
</listitem>
</orderedlist></para>
<para>You can extend
<classname>SQLErrorCodeSQLExceptionTranslator:</classname></para>
<programlisting language="java">public class CustomSQLErrorCodesTranslator extends SQLErrorCodeSQLExceptionTranslator {
protected DataAccessException customTranslate(String task, String sql, SQLException sqlex) {
if (sqlex.getErrorCode() == -12345) {
return new DeadlockLoserDataAccessException(task, sqlex);
}
return null;
}
}</programlisting>
<para>In this example, the specific error code <literal>-12345</literal>
is translated and other errors are left to be translated by the default
translator implementation. To use this custom translator, it is
necessary to pass it to the <classname>JdbcTemplate</classname> through
the method <literal>setExceptionTranslator</literal> and to use this
<classname>JdbcTemplate</classname> for all of the data access
processing where this translator is needed. Here is an example of how
this custom translator can be used:</para>
<programlisting language="java"><lineannotation>private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
// create a JdbcTemplate and set data source</lineannotation>
this.jdbcTemplate = new JdbcTemplate();
this.jdbcTemplate.setDataSource(dataSource);
<lineannotation> // create a custom translator and set the DataSource for the default translation lookup</lineannotation>
CustomSQLErrorCodesTranslator tr = new CustomSQLErrorCodesTranslator();
tr.setDataSource(dataSource);
this.jdbcTemplate.setExceptionTranslator(tr);
}
<lineannotation>public void updateShippingCharge(long orderId, long pct) {
// use the prepared JdbcTemplate for this update</lineannotation>
this.jdbcTemplate.update(
"update orders" +
" set shipping_charge = shipping_charge * ? / 100" +
" where id = ?"
pct, orderId);
}</programlisting>
<para>The custom translator is passed a data source in order to look up
the error codes in <literal>sql-error-codes.xml</literal>.</para>
</section>
<section xml:id="jdbc-statements-executing">
<title>Executing statements</title>
<para>Executing an SQL statement requires very little code. You need a
<interfacename>DataSource</interfacename> and a
<classname>JdbcTemplate</classname>, including the convenience
methods<!--Does reader know what you mean by *convenience* methods? TR: OK as is. I hope they know what this is.-->
that are provided with the <classname>JdbcTemplate</classname>. The
following example shows what you need to include for a minimal but fully
functional class that creates a new table:</para>
<programlisting language="java">import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class ExecuteAStatement {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void doExecute() {
this.jdbcTemplate.execute("create table mytable (id integer, name varchar(100))");
}
}</programlisting>
</section>
<section xml:id="jdbc-statements-querying">
<title>Running queries</title>
<para>Some query methods return a single value. To retrieve a count or a
specific value from one row, use
<methodname>queryForInt(..)</methodname>,
<methodname>queryForLong(..)</methodname> or
<methodname>queryForObject(..)</methodname>. The latter converts the
returned JDBC <classname>Type</classname> to the Java class that is
passed in as an argument. If the type conversion is invalid, then an
<exceptionname>InvalidDataAccessApiUsageException</exceptionname> is
thrown. Here is an example that contains two query methods, one for an
<classname>int</classname> and one that queries for a
<classname>String</classname>.</para>
<programlisting language="java">import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class RunAQuery {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public int getCount() {
return this.jdbcTemplate.queryForInt("select count(*) from mytable");
}
public String getName() {
return (String) this.jdbcTemplate.queryForObject("select name from mytable", String.class);
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}</programlisting>
<para>In addition to the single result query methods, several methods
return a list with an entry for each row that the query returned. The
most generic method is <methodname>queryForList(..)</methodname> which
returns a <interfacename>List</interfacename> where each entry is a
<interfacename>Map</interfacename> with each entry in the map
representing the column value for that row. If you add a method to the
above example to retrieve a list of all the rows, it would look like
this:</para>
<programlisting language="java">
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Map<String, Object>> getList() {
return this.jdbcTemplate.queryForList("select * from mytable");
}</programlisting>
<para>The list returned would look something like this:</para>
<programlisting>[{name=Bob, id=1}, {name=Mary, id=2}]</programlisting>
</section>
<section xml:id="jdbc-updates">
<title>Updating the database</title>
<para>The following example shows a column updated for a certain primary
key. In this example, an SQL statement has placeholders for row
parameters. The parameter values can be passed in as varargs or
alternatively as an array of objects. Thus primitives should be wrapped
in the primitive wrapper classes explicitly or using auto-boxing.</para>
<programlisting language="java">import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class ExecuteAnUpdate {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void setName(int id, String name) {
this.jdbcTemplate.update(
"update mytable set name = ? where id = ?",
name, id);
}
}</programlisting>
</section>
<section xml:id="jdbc-auto-genereted-keys">
<title>Retrieving auto-generated keys</title>
<para>An <methodname>update()</methodname> convenience method
supports<!--Give name of this method. Also indicate *what* is acquiring the primary keys. TR: Changed to *retrieval*.
The name of the method is *update*.--> the retrieval of primary keys generated
by the database. This support is part of the JDBC 3.0 standard; see
Chapter 13.6 of the specification for details. The method takes a
<classname>PreparedStatementCreator</classname> as its first argument,
and this is the way the required insert statement is specified. The
other argument is a <classname>KeyHolder</classname>, which contains the
generated key on successful return from the update. There is not a
standard single way to create an appropriate
<classname>PreparedStatement</classname> (which explains why the method
signature is the way it is). The following example works on Oracle but
may not work on other platforms:</para>
<programlisting language="java">final String INSERT_SQL = "insert into my_test (name) values(?)";
final String name = "Rob";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps =
connection.prepareStatement(INSERT_SQL, new String[] {"id"});
ps.setString(1, name);
return ps;
}
},
keyHolder);
<lineannotation>// keyHolder.getKey() now contains the generated key</lineannotation></programlisting>
</section>
</section>
<section xml:id="jdbc-connections">
<title>Controlling database connections</title>
<section xml:id="jdbc-datasource">
<title><interfacename>DataSource</interfacename><!--I don't understand why *DataSource* was a subsection of *Using the JDBC classes to control basic JDBC processing and error handling*.--><!--According to *The package hierarchy*section, there is a datasource package, separate from the core package.So I moved it to this section. TR: OK.--></title>
<para>Spring obtains a connection to the database through a
<interfacename>DataSource</interfacename>. A
<interfacename>DataSource</interfacename> is part of the JDBC
specification and is a generalized connection factory. It allows a
container or a framework to hide connection pooling and transaction
management issues from the application code. As a developer, you need
not know details about how to connect to the database; that is the
responsibility of the administrator that sets up the datasource. You
most likely fill both roles as you develop and test code, but you do not
necessarily have to know how the production data source is
configured.</para>
<para>When using Spring's JDBC layer, you obtain a data source from JNDI
or you configure your own with a connection pool implementation provided
by a third party. Popular implementations are Apache Jakarta Commons
DBCP and C3P0. Implementations in the Spring distribution are meant only
for testing purposes and do not provide pooling.</para>
<para>This section uses Spring's
<classname>DriverManagerDataSource</classname> implementation, and
several additional implementations are covered later.</para>
<para><note>
<para>Only use the <classname>DriverManagerDataSource</classname>
class should only be used for testing purposes since it does not
provide pooling and will perform poorly when multiple requests for a
connection are made.</para>
</note>You obtain a connection with