Listing 8-44. The InsertContact Class
package com.apress.prospring3.ch8.dao.jdbc.annotation;
import java.sql.Types;
import javax.sql.DataSource;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.SqlUpdate;
public class InsertContact extends SqlUpdate {
private static final String SQL_INSERT_CONTACT =
"insert into contact (first_name, last_name, birth_date) values (:first_name,
:last_name, :birth_date)";
public InsertContact(DataSource dataSource) {
super(dataSource, SQL_INSERT_CONTACT);
super.declareParameter(new SqlParameter("first_name", Types.VARCHAR));
super.declareParameter(new SqlParameter("last_name", Types.VARCHAR));
super.declareParameter(new SqlParameter("birth_date", Types.DATE));
super.setGeneratedKeysColumnNames(new String[] {"id"});
super.setReturnGeneratedKeys(true);
}
}
The InsertContact class is almost the same as the UpdateContact class. We just need to do two more
things. When constructing the InsertContact class, we call the method
SqlUpdate.setGeneratedKeysColumnNames() to declare the name of the ID column. The method
SqlUpdate.setReturnGeneratedKeys() instructs the underlying JDBC driver to retrieve the generated key.
Listing 8-45 shows the implementation of the insert() method in the JdbcContactDao class.
Listing 8-45. Using SqlUpdate for Insert Operation
package com.apress.prospring3.ch8.dao.jdbc.annotation;
// Import statements omitted
@Repository("contactDao")
public class JdbcContactDao implements ContactDao {
private InsertContact insertContact;
@Resource(name="dataSource")
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
selectAllContacts = new SelectAllContacts(dataSource);
selectContactByFirstName = new SelectContactByFirstName(dataSource);
updateContact = new UpdateContact(dataSource);
insertContact = new InsertContact(dataSource);
}
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home