(自己学习,做的小例子,记录一下)
使用flex.data.DataServiceTransaction类来实现server push,当server端的数据发生变化时,将改变自动推向client端。
有两种不同的方法:
1. 使用DataServiceTransaction实例,DataServiceTransaction实例是为每个汇编操作创建的,汇编操作是修改了数据管理服务来管理对象的状态。
2. 通过自己的代码来创建DataServiceTransaction实例。
第一种方法:(使用汇编操作被调用时创建的DataServiceTransaction实例),调用它的static
getCurrentDataServiceTransaction() 方法,接着调用它的updateitem(),deleteitem()或createitem()方法来触发额外的改变,调用这些方法来apply在这个事务中你已经维持或即将维持的修改,如果当前事务回滚,这些改变将不会push到客户端。
第二种方法:(不需要一个DataServiceTransaction实例),你可以调用static DataServiceTransaction.begin()方法来初始化一个事务.
具体步骤:需要编写自己的DAO和连接数据库的类,DAO包括一些操作数据库的方法,其中创建对象的方法要将所创建对象的主键id返回,并设置到当前内存中的该对象。
创建对象并push到客户端的例子:
BaseDAO.java
public int createItem(String sql, Object[] params) throws DAOException {
Connection c = null;
try {
c = ConnectionHelper.getConnection();
executeUpdate(sql, params, c);
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT LAST_INSERT_ID()");
int keyValue = -1;
if (rs.next()) {
keyValue = rs.getInt(1);
}
return keyValue;
} catch (SQLException e) {
e.printStackTrace();
throw new DAOException(e);
} finally {
ConnectionHelper.close(c);
}
}
ProductDAO.java继承BaseDAO
public void create(Product product) throws Exception{
int accountId = createItem("INSERT INTO product(description, price, productname) VALUES (?,?,?)",
new Object[] { product.getDescription(),product.getPrice(),product.getProductname()
});
product.setProductid(accountId);
}
前台调用的servlet
DataServiceTransaction dst=DataServiceTransaction.begin(false);
Product prod = new Product();
prod.setProductname("Product1");
prod.setDescription("A great product");
prod.setPrice(10f);
ProductDAO pa=new ProductDAO();
try {
pa.create(prod);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Inform the Data Management Service:
dst.createItem("NewModel.Product", prod);//("NewModel.Product"是client端service对应的destination)
dst.commit();
配置好servlet,前台发送httpservice请求。执行效果就是数据库数据更新后,前台绑定的data也会自动更新。