25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9 ■ Adding Persistence to Your <strong>Spring</strong> Application<br />

Listing 9-15 shows how you can reduce the amount of code by using the JdbcTemplate class, where you can pass<br />

the query and the row mapper. The JdbcTemplate implements a Template Design pattern that does the heavy work of<br />

calling the JDBC directly, and therefore provides easy methods for executing SQL statements.<br />

Next, let’s create the DocumentRowMapper class as shown in Listing 9-16.<br />

Listing 9-16. DocumentRowMapper<br />

package com.apress.isf.spring.jdbc;<br />

import java.sql.ResultSet;<br />

import java.sql.SQLException;<br />

import org.springframework.jdbc.core.RowMapper;<br />

import com.apress.isf.java.model.Document;<br />

import com.apress.isf.java.model.Type;<br />

public class DocumentRowMapper implements RowMapper {<br />

}<br />

public Document mapRow(ResultSet rs, int rowNum) throws SQLException {<br />

Document document = new Document();<br />

document.setDocumentId(rs.getString("documentId"));<br />

document.setName(rs.getString("name"));<br />

document.setLocation(rs.getString("location"));<br />

document.setCreated(rs.getDate("created"));<br />

document.setModified(rs.getDate("modified"));<br />

document.setDescription("doc_desc");<br />

Type type = new Type();<br />

type.setTypeId(rs.getString("typeId"));<br />

type.setName(rs.getString("type_name"));<br />

type.setDesc(rs.getString("type_desc"));<br />

type.setExtension(rs.getString("extension"));<br />

document.setType(type);<br />

return document;<br />

}<br />

Listing 9-16 shows how to implement the RowMapper interface. You can see that the <strong>Spring</strong> <strong>Framework</strong> will<br />

iterate every row and create the result list you need: the Document model. If you take this approach, you will have more<br />

readable code.<br />

Next, let’s create the XML configuration that will contain the new reference to the<br />

DocumentJdbcTemplateRepository class as shown in Listing 9-17.<br />

Listing 9-17. mydocuments-jdb-template-context.xml<br />

<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!