public void insert(Contact contact) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("first_name", contact.getFirstName());
paramMap.put("last_name", contact.getLastName());
paramMap.put("birth_date", contact.getBirthDate());
KeyHolder keyHolder = new GeneratedKeyHolder();
insertContact.updateByNamedParam(paramMap, keyHolder);
contact.setId(keyHolder.getKey().longValue());
log.info("New contact inserted with id: " + contact.getId());
}
// Other code omitted
}
From Listing 8-45, upon data source injection, an instance of InsertContact was constructed (note
the lines in bold). In the insert() method, we also use the SqlUpdate.updateByNamedParam() method.
However, we also pass in an instance of KeyHolder to the method, which will have the generated ID
stored. After the data is inserted, we can then retrieve the generated key from the KeyHolder.
To test the operation, add the code snippet in Listing 8-46 into the AnnotationJdbcDaoSample class.
Listing 8-46. Testing the insert() Method
// Insert contact
contact = new Contact();
contact.setFirstName("Rod");
contact.setLastName("Johnson");
contact.setBirthDate(new Date((new GregorianCalendar(2001, 10,
1)).getTime().getTime()));
contactDao.insert(contact);
contacts = contactDao.findAll();
listContacts(contacts);
Running the program will produce the following output from the last listContacts() method:
11:36:08,871  INFO 3.ch8.dao.jdbc.annotation.JdbcContactDao:  88 - New contact inserted with
id: 4
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
Contact - Id: 4, First name: Rod, Last name: Johnson, Birthday: 2001-11-01
You can see that the new contact was inserted with an ID of 4 and retrieved correctly.
Batching Operations with BatchSqlUpdate
For batch operation, we use the BatchSqlUpdate class. The use is basically the same as the SqlUpdate
class; we just need to do a few more things. To demonstrate its usage, let's add a new method into the
ContactDao interface:
public void insertWithDetail(Contact contact);
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home