`
wangyisong
  • 浏览: 238142 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

跟我StepByStep学FLEX教程------Demo13之Flex访问数据库

    博客分类:
  • FLEX
阅读更多

跟我StepByStep学FLEX教程------Demo13之Flex访问数据库

 

 

说明:该文系作者原创,请勿商用或者用于论文发表,转载必须经作者同意并且注明出处。

 

 

      Demo13通过Spring的JdbcTemplate方式访问数据库,数据库选择使用hsqldb(读者也可以选用mysql、oracle、sqlserver等等)。

      必须的,把hsqldb和spring相关jar包拷贝到lib下(提示,如果读者没有看DEMO11和DEMO12,那就必须看一下,因为这些DEMO一个是一个的基础)。

      配置文件不重复以前DEMO的配置,呵呵:)

      这个Demo大家可以访问http://coenraets.org/downloads/flex-spring.zip网址,下一下代码,这个Demo的代码都用得这里边的(比较经典的,作者也省得再去编写了,哈哈,刚好下一个Demo使用Hibernate就在此基础上整合就行)。

 

      1、配置数据源(很显然,这个也是使用Spring方式,Spring是不是无处不在啊,呵呵)。在applicationContext.xml中增加datasource的配置,如下:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:file:FilePath(读者的数据库文件路径)"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>

       2、增加业务层代码,如下:

       Product.java(持久层对象)

package com.samples.spring.store;

public class Product {

 private long productId;

 private String name;

 private String description;

 private String image;

 private String category;

 private double price;
 
 private int qtyInStock;

 public String getCategory() {
  return category;
 }

 public void setCategory(String category) {
  this.category = category;
 }

 public String getDescription() {
  return description;
 }

 public void setDescription(String description) {
  this.description = description;
 }

 public String getImage() {
  return image;
 }

 public void setImage(String image) {
  this.image = image;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public double getPrice() {
  return price;
 }

 public void setPrice(double price) {
  this.price = price;
 }

 public long getProductId() {
  return productId;
 }

 public void setProductId(long productId) {
  this.productId = productId;
 }

 public int getQtyInStock() {
  return qtyInStock;
 }

 public void setQtyInStock(int qtyInStock) {
  this.qtyInStock = qtyInStock;
 }
 

}

     ProductDAO.java(业务层接口)

package com.samples.spring.store;

import java.util.Collection;
import org.springframework.dao.DataAccessException;

public interface ProductDAO {

 public Collection findAll() throws DataAccessException ;
 
 public void createProduct(Product product) throws DataAccessException ;
 
 public void updateProduct(Product product) throws DataAccessException ;
 
 public void deleteProduct(Product product) throws DataAccessException ;
 
}

     SimpleProductDAO.java(业务层实现)

package com.samples.spring.store;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class SimpleProductDAO extends JdbcDaoSupport implements ProductDAO {
 
 public Collection findAll() throws DataAccessException {
  String sql = "SELECT * FROM product";
  
  RowMapper mapper = new RowMapper() {
   
   public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
    Product product = new Product();
    product.setProductId(rs.getLong("product_id"));
    product.setName(rs.getString("name"));
    product.setDescription(rs.getString("description"));
    product.setCategory(rs.getString("category"));
    product.setImage(rs.getString("image"));
    product.setPrice(rs.getDouble("price"));
    product.setQtyInStock(rs.getInt("qty_in_stock"));
    return product;
   }
   
  };
  
  JdbcTemplate template = new JdbcTemplate(this.getDataSource());
  System.out.println("sql" + sql + "mapper" + mapper.toString());
  return template.query(sql, mapper);
 }

 public void createProduct(Product product) throws DataAccessException {
  String sql = "INSERT INTO product (name, description, category, image, price, qty_in_stock) VALUES (:name, :description, :category, :image, :price, :qtyInStock)";
  NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(this.getDataSource());
  SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(product);
  template.update(sql, namedParameters);
  product.setProductId(getJdbcTemplate().queryForInt("call identity()"));
 }

 public void updateProduct(Product product) throws DataAccessException {
  String sql = "UPDATE product SET name=:name,description=:description,category=:category,image=:image,price=:price,qty_in_stock=:qtyInStock WHERE product_id=:productId";
  NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(this.getDataSource());
  SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(product);
  template.update(sql, namedParameters);
 }

 public void deleteProduct(Product product) throws DataAccessException {
  String sql = "DELETE from product WHERE product_id=:productId";
  NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(this.getDataSource());
  SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(product);
  template.update(sql, namedParameters);
 }

}

     3、在applicationContext.xml中配置bean,如下:

<bean id="productDAOBean" class="com.samples.spring.store.SimpleProductDAO">
        <property name="dataSource" ref="dataSource"/>
    </bean>

     4、在remoting-config.xml中配置向Flex客户端公开的bean,如下:

<destination id="productService">
     <properties>
         <factory>spring</factory>
         <source>productDAOBean</source>
     </properties>
 </destination>

     5、接下来就是Flex客户端的代码了

     HelloFlexPro.mxml(主文件)

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="absolute" creationComplete="srv.findAll()"> 
 <mx:Script>
 <![CDATA[
  import mx.rpc.events.ResultEvent;
  import mx.controls.Alert;
  import mx.rpc.events.FaultEvent;
   
  private function findAllFaultHandler(event:FaultEvent):void
  {
   Alert.show(event.fault.faultString, "Error");
  }
 ]]>
 </mx:Script>
 <mx:RemoteObject id="srv" destination="productService">
  <mx:method name="findAll" fault="findAllFaultHandler(event)"/>
 </mx:RemoteObject>
 
 <mx:HDividedBox width="100%" height="100%">

  <mx:Panel title="Inventory Management" width="100%" height="100%">
   <mx:DataGrid id="list" width="100%" height="100%" dataProvider="{srv.findAll.lastResult}">
    <mx:columns>
     <mx:DataGridColumn dataField="name" headerText="Name"/>
     <mx:DataGridColumn dataField="category" headerText="Name"/>
     <mx:DataGridColumn dataField="qtyInStock" headerText="In Stock"/>
    </mx:columns>
   </mx:DataGrid>
  </mx:Panel>
  
  <ProductForm product="{Product(list.selectedItem)}"/>

 </mx:HDividedBox>
</mx:Application>
      Product.as(Flex页面使用类)

package {
 //[Managed]
 [RemoteClass(alias="com.samples.spring.store.Product")]
 public class Product
 {
  public function Product()
  {
  }

  public var productId:int;

  public var name:String;

  public var category:String;

  public var price:Number;

  public var image:String;

  public var description:String;
  
  public var qtyInStock:int;

 }
}

      ProductForm.mxml(列表的页面代码)

<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*"
 title="Details" width="100%" height="100%">
 
 <Product id="product"
  name="{productName.text}"
  category="{category.text}"
  price="{Number(price.text)}"
  qtyInStock="{int(qtyInStock.text)}"
  image="{image.text}"
  description="{description.text}"/>

 <mx:RemoteObject id="srv" destination="productService"/>

 <mx:Form width="100%">
 
  <mx:FormItem label="Name">
   <mx:TextInput id="productName" text="{product.name}"/>
  </mx:FormItem>
 
  <mx:FormItem label="Category">
   <mx:TextInput id="category" text="{product.category}"/>
  </mx:FormItem>
  
  <mx:FormItem label="Image">
   <mx:TextInput id="image" text="{product.image}"/>
  </mx:FormItem>
  
  <mx:FormItem label="Price">
   <mx:TextInput id="price" text="{product.price}"/>
  </mx:FormItem>

  <mx:FormItem label="In Stock">
   <mx:TextInput id="qtyInStock" text="{product.qtyInStock}"/>
  </mx:FormItem>
 
  <mx:FormItem label="Description" width="100%">
   <mx:TextArea id="description" text="{product.description}" width="100%" height="100"/>
  </mx:FormItem>
  
 </mx:Form>

 <mx:ControlBar>
  <mx:Button label="Update" click="srv.updateProduct(product)"/>
 </mx:ControlBar>

</mx:Panel>

       6、运行,如下界面:



 

      哈哈,其实就是这么简单,下一讲集成Hibernate,就在这个Demo的基础上进行改造,所以读者从Demo11开始必须每一讲都认真看,否则后边的Demo就无法按步骤操作运行了。

 

       附:数据库脚本

CREATE SCHEMA PUBLIC AUTHORIZATION DBA
CREATE MEMORY TABLE PRODUCT(PRODUCT_ID INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,NAME VARCHAR(40),CATEGORY VARCHAR(40),IMAGE VARCHAR(40),PRICE DOUBLE,QTY_IN_STOCK INTEGER,DESCRIPTION VARCHAR(255))
ALTER TABLE PRODUCT ALTER COLUMN PRODUCT_ID RESTART WITH 20
CREATE USER SA PASSWORD ""
GRANT DBA TO SA
SET WRITE_DELAY 20
SET SCHEMA PUBLIC
INSERT INTO PRODUCT VALUES(1,'Nokia 6010','6000','Nokia_6010.gif',99.99E0,12,'Easy to use without sacrificing style, the Nokia 6010 phone offers functional voice communication supported by text messaging, multimedia messaging, mobile internet, games and more.')
INSERT INTO PRODUCT VALUES(2,'Nokia 3100 Blue','9000','Nokia_3100_blue.gif',149.0E0,20,'Light up the night with a glow-in-the-dark cover - when it is charged with light you can easily find your phone in the dark. When you get a call, the Nokia 3100 phone flashes in tune with your ringing tone. And when you snap on a Nokia Xpress-on gaming cover, you will get luminescent light effects in time to the gaming action.')
INSERT INTO PRODUCT VALUES(3,'Nokia 3100 Pink','3000','Nokia_3100_pink.gif',139.0E0,50,'Light up the night with a glow-in-the-dark cover - when it is charged with light you can easily find your phone in the dark. When you get a call, the Nokia 3100 phone flashes in tune with your ringing tone. And when you snap on a Nokia Xpress-on gaming cover, you will get luminescent light effects in time to the gaming action.')
INSERT INTO PRODUCT VALUES(4,'Nokia 3120','3000','Nokia_3120.gif',159.99E0,40,'Designed for both business and pleasure, the elegant Nokia 3120 phone offers a pleasing mix of features. Enclosed within its chic, compact body, you will discover the benefits of tri-band compatibility, a color screen, MMS, XHTML browsing, cheerful screensavers, and much more.')
INSERT INTO PRODUCT VALUES(5,'Nokia 3220','3000','Nokia_3220.gif',200.0E0,20,'The Nokia 3220 phone is a fresh new cut on some familiar ideas - animate your MMS messages with cute characters, see the music with lights that flash in time with your ringing tone, download wallpapers and screensavers with matching color schemes for the interface.')
INSERT INTO PRODUCT VALUES(6,'Nokia 3650','3000','Nokia_3650.gif',200.0E0,15,'Messaging is more personal, versatile and fun with the Nokia 3650 camera phone.  Capture experiences as soon as you see them and send the photos you take to you friends and family.')
INSERT INTO PRODUCT VALUES(7,'Nokia 6820','6000','Nokia_6820.gif',299.99E0,68,'Messaging just got a whole lot smarter. The Nokia 6820 messaging device puts the tools you need for rich communication - full messaging keyboard, digital camera, mobile email, MMS, SMS, and Instant Messaging - right at your fingertips, in a small, sleek device.')
INSERT INTO PRODUCT VALUES(8,'Nokia 6670','6000','Nokia_6670.gif',309.99E0,14,'Classic business tools meet your creative streak in the Nokia 6670 imaging smartphone. It has a Netfront Web browser with PDF support, document viewer applications for email attachments, a direct printing application, and a megapixel still camera that also shoots up to 10 minutes of video.')
INSERT INTO PRODUCT VALUES(9,'Nokia 6620','6000','Nokia_6620.gif',329.99E0,58,'Shoot a basket. Shoot a movie. Video phones from Nokia... the perfect way to save and share life\u2019s playful moments. Feel connected.')
INSERT INTO PRODUCT VALUES(10,'Nokia 3230 Silver','3000','Nokia_3230_black.gif',500.0E0,10,'Get creative with the Nokia 3230 smartphone. Create your own ringing tones, print your mobile images, play multiplayer games over a wireless Bluetooth connection, and browse HTML and xHTML Web pages. ')
INSERT INTO PRODUCT VALUES(11,'Nokia 6680','6000','Nokia_6680.gif',222.0E0,20,'The Nokia 6680 is an imaging smartphone that')
INSERT INTO PRODUCT VALUES(12,'Nokia 6630','6000','Nokia_6630.gif',379.0E0,44,'The Nokia 6630 imaging smartphone is a 1.3 megapixel digital imaging device (1.3 megapixel camera sensor, effective resolution 1.23 megapixels for image capture, image size 1280 x 960 pixels).')
INSERT INTO PRODUCT VALUES(14,'Nokia 7610 White','7000','Nokia_7610_white.gif',399.99E0,85,'The Nokia 7610 imaging phone with its sleek, compact design stands out in any crowd. Cut a cleaner profile with a megapixel camera and 4x digital zoom. Quality prints are all the proof you need of your cutting edge savvy.')
INSERT INTO PRODUCT VALUES(15,'Nokia 6680','6000','Nokia_6680.gif',222.0E0,10,'The Nokia 6680 is an imaging smartphone.')
INSERT INTO PRODUCT VALUES(16,'Nokia 9300','9000','Nokia_9300_close.gif',599.0E0,20,'The Nokia 9300 combines popular voice communication features with important productivity applications in one well-appointed device. Now the tools you need to stay in touch and on top of schedules, email, news, and messages are conveniently at your fingertips.')
INSERT INTO PRODUCT VALUES(17,'Nokia 9500','9000','Nokia_9500_close.gif',799.99E0,58,'Fast data connectivity with Wireless LAN. Browse the Internet in full color, on a wide, easy-to-view screen. Work with office documents not just email with attachments and memos, but presentations and databases too.')
INSERT INTO PRODUCT VALUES(18,'Nokia N90','9000','Nokia_N90.gif',999.0E0,10,'Twist and shoot. It is a pro-photo taker. A personal video-maker. Complete with Carl Zeiss Optics for crisp, bright images you can view, edit, print and share. Meet the Nokia N90.')

  • 大小: 78.8 KB
4
1
分享到:
评论
8 楼 semovy 2010-07-29  
点击list时,flash player10弹出错

TypeError: Error #1034: 强制转换类型失败:无法将 Object@28444c1 转换为 Product。
at Function/<anonymous>()[H:\test\test pro\myeclipse\FlexSpringHsqlDB\flex_src\FlexSpringHsqlDB.mxml:27]
at Function/http://adobe.com/AS3/2006/builtin::apply()
at mx.binding::Binding/wrapFunctionCall()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\binding\Binding.as:287]
at mx.binding::Binding/innerExecute()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\binding\Binding.as:359]
at Function/http://adobe.com/AS3/2006/builtin::apply()
at mx.binding::Binding/wrapFunctionCall()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\binding\Binding.as:287]
at mx.binding::Binding/execute()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\binding\Binding.as:230]
at mx.binding::Binding/watcherFired()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\binding\Binding.as:396]
at mx.binding::Watcher/notifyListeners()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\binding\Watcher.as:299]
at mx.binding::PropertyWatcher/eventHandler()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\binding\PropertyWatcher.as:327]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.core::UIComponent/dispatchEvent()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:9298]
at mx.controls.listClasses::ListBase/mouseUpHandler()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\controls\listClasses\ListBase.as:8989]
at mx.controls::DataGrid/mouseUpHandler()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\controls\DataGrid.as:4337]
7 楼 zsq007 2010-03-19  
我忘了数据库驱动包!~  
6 楼 zsq007 2010-03-19  
访问数据库这部分例子都需要哪些spring包呢? 我按教程走了两遍还是404 错误
HTTP Status 404 - /Test-Flex-Spring-hsqldb/Flex/HelloFlexPro.html

--------------------------------------------------------------------------------

type Status report

message /Test-Flex-Spring-hsqldb/Flex/HelloFlexPro.html

description The requested resource (/Test-Flex-Spring-hsqldb/Flex/HelloFlexPro.html) is not available.
5 楼 lichuhui 2009-11-20  
请问楼主报这个错误是什么引起的?
引用

org.springframework.jdbc.CannotGetJdbcConnectionException : Could not get JDBC Connection; nested exception is java.sql.SQLException: Database lock acquisition failure: lockFile: org.hsqldb.persist.LockFile@22465527[file =D:\hsqldb\data\testdb.lck, exists=true, locked=false, valid=false, ] method: checkHeartbeat read: 2009-11-20 07:12:16 heartbeat - read: -5424 ms.
4 楼 lichuhui 2009-11-20  
请问楼主报这个错误是什么引起的?
org.springframework.jdbc.CannotGetJdbcConnectionException : Could not get JDBC Connection; nested exception is java.sql.SQLException: Database lock acquisition failure: lockFile: org.hsqldb.persist.LockFile@22465527[file =D:\hsqldb\data\testdb.lck, exists=true, locked=false, valid=false, ] method: checkHeartbeat read: 2009-11-20 07:12:16 heartbeat - read: -5424 ms.
3 楼 eclipse2008 2009-07-08  
wangyisong 写道
eclipse2008 写道
<ProductForm product="{Product(list.selectedItem)}"/>


public class Product
{
  public function Product()
  {
  }


不匹配吧?

文章所发布的多有代码都经过验证运行通过的,所以是匹配的,还有如果您运行不通过,看一下您的运行环境各部分的版本是否不一致(这种可能性应该很小)


thanks
2 楼 wangyisong 2009-07-07  
eclipse2008 写道
<ProductForm product="{Product(list.selectedItem)}"/>


public class Product
{
  public function Product()
  {
  }


不匹配吧?

文章所发布的多有代码都经过验证运行通过的,所以是匹配的,还有如果您运行不通过,看一下您的运行环境各部分的版本是否不一致(这种可能性应该很小)
1 楼 eclipse2008 2009-07-07  
<ProductForm product="{Product(list.selectedItem)}"/>


public class Product
{
  public function Product()
  {
  }


不匹配吧?

相关推荐

    跟我StepByStep学FLEX教程------王一松

    Demo13:Flex访问数据库 - **数据库连接**:介绍如何建立Flex应用与数据库之间的连接。 - **查询操作**:展示如何执行基本的SQL查询。 #### 30. Flex之Hibernate - **Hibernate介绍**:Hibernate是一个流行的...

    跟我StepByStep学FLEX教程-王一松.pdf

    14. 访问数据库:在Flex应用中访问数据库时,通常需要通过Java后端来实现,比如使用JDBCTemplate或Hibernate框架。Flex本身不能直接与数据库交互。 15. MVC设计模式:MVC(Model-View-Controller)是一种设计模式,...

    跟我StepByStep学FLEX教程.pdf

    跟我StepByStep学FLEX教程.pdf 跟我StepByStep学FLEX教程.pdf 跟我StepByStep学FLEX教程.pdf 跟我StepByStep学FLEX教程.pdf 跟我StepByStep学FLEX教程.pdf

    跟我StepByStep学FLEX教程 flex教程

    Flex教程详解:逐步掌握动态富互联网应用开发 Flex是由Adobe公司推出的一种用于构建富互联网应用程序(RIA)的技术,它基于ActionScript编程语言和MXML标记语言。本教程旨在引导学习者一步步深入理解Flex,帮助他们...

    跟我StepByStep学FLEX

    根据给定的信息,我们可以将《跟我StepByStep学FLEX》这本教程的主要知识点概括如下: ### FLEX基础 #### 概述 - **FLEX介绍**:FLEX是一种用于构建跨平台桌面应用程序和移动设备应用程序的技术。它结合了HTML、...

    StepByStep学FLEX教程.pdf

    - **Flex访问数据库**:通过具体实例演示如何让Flex应用程序直接访问数据库,并进行增删改查操作。 - **MVC架构**:最后,本教程还介绍了Cairngorm这一基于MVC模式的Flex架构框架。这部分将探讨Cairngorm的工作...

    flex-超好的flex学习资料

    《跟我StepByStep学FLEX教程》是由王一松编写的,旨在通过一系列深入浅出的示例,帮助读者从零开始掌握Flex的各项技术要点,从而能够独立开发出功能丰富、交互流畅的应用程序。 一、Flex入门与环境搭建 在《跟我...

    FLEX教程码源集合

    2. **跟我StepByStep学FLEX教程------王一松.pdf**:这是一本面向初学者的教程,由王一松编著。通过逐步的教学方式,讲解了Flex的基础知识,包括环境搭建、界面设计、事件处理、数据绑定等内容。适合没有FLEX背景的...

    安装算量(实例体验)入门教程(StepByStep)---消防报警篇(2)知识.pdf

    《安装算量(实例体验)入门教程(StepByStep)---消防报警篇(2)》是一份关于建筑电气安装算量的详细指南,主要讲解了消防报警系统的布线与识别布置过程,以及工程图的分层管理。以下是教程中涉及的关键知识点: 1. **...

    安装算量(实例体验)入门教程(StepByStep)---消防水篇借鉴.pdf

    《安装算量(实例体验)入门教程(StepByStep)---消防水篇借鉴》 本文主要介绍了使用金格软件进行安装工程量计算的入门教程,特别是针对消防水系统的计算。教程分为七个章节,旨在帮助初学者逐步理解并掌握专业安装算...

    安装算量(实例体验)入门教程(StepByStep)---消防报警篇(2).pdf

    《安装算量(实例体验)入门教程(StepByStep)---消防报警篇(2)》是一份详尽的教程,旨在帮助初学者掌握安装算量软件的使用,特别是在消防报警系统的回路识别与布置方面。以下是对教程内容的详细解析: 在消防报警系统...

Global site tag (gtag.js) - Google Analytics