跟我StepByStep学FLEX教程------Demo13之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.')

weixin073智慧旅游平台开发微信小程序+ssm后端毕业源码案例设计 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
python017基于Python贫困生资助管理系统带vue前后端分离毕业源码案例设计 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值