flex访问数据库:跟我StepByStep学FLEX教程------Demo13的Flex访问数据库

  Demo13通过SpringJdbcTemplate方式访问数据库数据库选择使用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" ="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 Product {

 private long productId;

 private String name;

 private String description;

 private String image;

 private String category;

 private double price;
 
 private qtyInStock;

 public String getCategory {
   category;
 }

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

 public String getDescription {
   description;
 }

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

 public String getImage {
   image;
 }

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

 public String getName {
   name;
 }

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

 public double getPrice {
   price;
 }

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

 public long getProductId {
   productId;
 }

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

 public getQtyInStock {
   qtyInStock;
 }

 public void QtyInStock( qtyInStock) {
  this.qtyInStock = qtyInStock;
 }
 

}


  ProductDAO.java(业务层接口)

package com.samples.spring.store;

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

public erface 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 SimpleProductDAO extends JdbcDaoSupport implements ProductDAO {
 
 public Collection findAll throws DataAccessException {
  String sql = "SELECT * FROM product";
  
  RowMapper mapper = RowMapper {
   
   public Object mapRow(ResultSet rs, rowNum) throws SQLException {
    Product product = Product;
    product.ProductId(rs.getLong("product_id"));
    product.Name(rs.getString("name"));
    product.Description(rs.getString("description"));
    product.Category(rs.getString("category"));
    product.Image(rs.getString("image"));
    product.Price(rs.getDouble("price"));
    product.QtyInStock(rs.getInt("qty_in_stock"));
     product;
   }
   
  };
  
  JdbcTemplate template = JdbcTemplate(this.getDataSource);
  .out.prln("sql" + sql + "mapper" + mapper.toString);
   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 = NamedParameterJdbcTemplate(this.getDataSource);
  SqlParameterSource namedParameters = BeanPropertySqlParameterSource(product);
  template.update(sql, namedParameters);
  product.ProductId(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 = NamedParameterJdbcTemplate(this.getDataSource);
  SqlParameterSource namedParameters = BeanPropertySqlParameterSource(product);
  template.update(sql, namedParameters);
 }

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

}


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

<bean id="productDAOBean" ="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 Product
 {
  public function Product
  {
  }

  public var productId:;

  public var name:String;

  public var category:String;

  public var price:Number;

  public var image:String;

  public var description:String;
  
  public var qtyInStock:;

 }
}


  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="{(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、运行如下界面:

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

  图片看不清楚?请点击这里查看原图(大图)

  哈哈其实就是这么简单讲集成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.g',99.99E0,12,'Easy to use without sacricing style, the Nokia 6010 phone offers functional voice communication supported by text messaging, multimedia messaging, mobile ernet, games and more.')
INSERT INTO PRODUCT VALUES(2,'Nokia 3100 Blue','9000','Nokia_3100_blue.g',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.g',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.g',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.g',200.0E0,20,'The Nokia 3220 phone is a fresh 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 erface.')
INSERT INTO PRODUCT VALUES(6,'Nokia 3650','3000','Nokia_3650.g',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.g',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.g',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 pring 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.g',329.99E0,58,'Shoot a basket. Shoot a movie. Video phones from Nokia... the perfect way to save and share le\u2019s playful moments. Feel connected.')
INSERT INTO PRODUCT VALUES(10,'Nokia 3230 Silver','3000','Nokia_3230_black.g',500.0E0,10,'Get creative with the Nokia 3230 smartphone. Create your own ringing tones, pr 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.g',222.0E0,20,'The Nokia 6680 is an imaging smartphone that')
INSERT INTO PRODUCT VALUES(12,'Nokia 6630','6000','Nokia_6630.g',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.g',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 prs are all the proof you need of your cutting edge savvy.')
INSERT INTO PRODUCT VALUES(15,'Nokia 6680','6000','Nokia_6680.g',222.0E0,10,'The Nokia 6680 is an imaging smartphone.')
INSERT INTO PRODUCT VALUES(16,'Nokia 9300','9000','Nokia_9300_close.g',599.0E0,20,'The Nokia 9300 combines popular voice communication features with important productivity applications in one well-appoed device. Now the tools you need to stay in touch and on top of schedules, email, s, and messages are conveniently at your fingertips.')
INSERT INTO PRODUCT VALUES(17,'Nokia 9500','9000','Nokia_9500_close.g',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.g',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, pr and share. Meet the Nokia N90.')




  文章来源:http://wangyisong.javaeye.com/blog/421149



Tags:  flex入门教程 flex3教程 flex教程 flex访问数据库

延伸阅读

最新评论

发表评论