InSync01:查找联系人
一、运行DEMO:
1、运行程序:http://localhost:8400/spring-flex-testdrive/insync01/index.html;
2、单击Search按钮,从数据库获取所有的联系人。
3、在Search文本框输入几个字符,单击“Search”按钮,按名字来查找联系人。
二、理解代码:
1、insync01.mxml文件:
定义远程对象,
<s:RemoteObject id="ro" destination="contactService" endpoint="http://localhost:8400/spring-flex-testdrive/messagebroker/amf"/>
Search的单击事件处理代码是:ro.findByName(searchStr.text)
2、配置文件
flex-servlet.xml :
<flex:remoting-destination ref="contactService" />
app-config.xml :
<bean id="contactService" class="org.springframework.flex.samples.contact.ContactDAO">
??? <constructor-arg ref="dataSource" />
</bean>
3、org/springframework/flex/samples/contact/ContactDAO.java
构造函数实例化template(用于查找、更新、删除操作)和insertContact(用于插入操作)。
public ContactDAO(DataSource dataSource) {
??????? this.template = new SimpleJdbcTemplate(dataSource);
??????? this.insertContact = new SimpleJdbcInsert(dataSource).withTableName("CONTACT").usingGeneratedKeyColumns("ID");
??? }
按名称查找联系人的方法。
public List<Contact> findByName(String name) {
??????? return this.template.query("SELECT * FROM contact WHERE UPPER(CONCAT(first_name,' ',last_name)) LIKE ? ORDER BY first_name,last_name",
??????????? this.rowMapper,"%" + name.toUpperCase() + "%");
??? }
4、SimpleJdbcTemplate:
Spring的SimpleJdbcTemplate封装了常用的Jdbc操作,其中一个很方便的用法是在query查询数据库之后可以在ResultSet结果集中进行迭代,将结果集中的行转换为java对象。
SimpleJdbcTemplate的query方法格式如:
query(String sql,ParameterizedRowMapper<T> rm,SqlParameterSource args) 。
为了使用泛型简化操作,定义了Contact类,用于在数据库中返回值时进行数据行与JAVA对类的转换。
private final RowMapper<Contact> rowMapper = new ParameterizedRowMapper<Contact>() {
??????? public Contact mapRow(ResultSet rs,int rowNum) throws SQLException {
??????????? Contact contact = new Contact();
??????????? contact.setId(rs.getInt("id"));
??????????? contact.setFirstName(rs.getString("first_name"));
??????????? contact.setLastName(rs.getString("last_name"));
??????????? contact.setAddress(rs.getString("address"));
??????????? contact.setCity(rs.getString("city"));
??????????? contact.setState(rs.getString("state"));
??????????? contact.setZip(rs.getString("zip"));
??????????? contact.setPhone(rs.getString("phone"));
??????????? contact.setEmail(rs.getString("email"));
??????????? return contact;
??????? }
??? };
?
?三、小结:
这个例子显示了一个查询操作,从Flex到在DAO中使用Spring提供的JDBC API来操作数据库。这个例子展示的架构中的主要过程简化为:RemoteObject->flex:remoting-destination->Spring bean->Spring JdbcTemplate->H2 DB