In Listing 8-42, upon data source injection, an instance of UpdateContact is constructed (note the
lines in bold). In the update() method, a HashMap of named parameters is constructed from the pass in
Contact object, and then the updateByNamedParam() is called to update the contact record. To test the
operation, add the code snippet in Listing 8-43 into the AnnotationJdbcDaoSample class.
Listing 8-43. Testing the update() Method
Contact contact;
// Update contact
contact = new Contact();
contact.setId(1l);
contact.setFirstName("Clarence");
contact.setLastName("Peter");
contact.setBirthDate(new Date((new GregorianCalendar(1977, 10,
1)).getTime().getTime()));
contactDao.update(contact);
contacts = contactDao.findAll();
listContacts(contacts);
In Listing 8-43, we simply construct a Contact object and then invoke the update() method. Running
the program will produce the following output from the last listContacts() method:
11:12:27,020  INFO 3.ch8.dao.jdbc.annotation.JdbcContactDao:  87 - Existing contact updated
with id: 1
Contact - Id: 1, First name: Clarence, Last name: Peter, Birthday: 1977-11-01
Contact - Id: 2, First name: Scott, Last name: Tiger, Birthday: 1990-11-02
Contact - Id: 3, First name: John, Last name: Smith, Birthday: 1964-02-28
In the output, you can see that the contact with an ID of 1 was updated accordingly.
Inserting Data and Retrieving the Generated Key
For inserting data, we also use the SqlUpdate class. However, one interesting point here is about the
primary key, the id column, which will be available only after the insert statement has completed, while
the RDBMS generated the identity value for the record. The column ID was declared with the attribute
AUTO_INCREMENT and is the primary key, which means the value was assigned by the RDBMS during the
insert operation.
If you are using Oracle, you will probably get an unique ID first from an Oracle sequence and then
fire the insert statement with the query. However, for our case, how can we retrieve the key generated by
the RDBMS after the record is inserted?
In old versions of JDBC, the method is a bit tricky. For example, if we are using MySQL, we need to
fire the SQL select last_insert_id() and select @@IDENTITY for Microsoft SQL Server.
Luckily, starting from JDBC version 3.0, a new feature was added that allows the retrieval of a RDBMS-
generated key in a unified fashion. Listing 8-37 shows the implementation of the insert() method, which
also retrieves the generated key for the inserted contact record. It will work in most databases (if not all);
just make sure you are using a JDBC driver that is compatible with JDBC 3.0 or newer.
We start by creating the InsertContact class for the insert operation, which extends the SqlUpdate
class. Listing 8-44 shows the class.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home