Login
Username:

Password:

Remember me



Lost Password?

Register now!
Main Menu
Blogs - Entry for Admin
 Syndicate Admin's entries

2010/07/24
Flex 4 Sample Using BlazeDs 3, Java, Hibernate and MySQL
Category: Tutorials : Flex

Author: Admin (11:45 am)
Flex 4 Sample Using BlazeDs 3, Java, Hibernate and MySQL


By David Welford-Costelloe (http://www.welford-costelloe.com)


This document takes you through the complete setup of Flex 4 (Beta 2) to get data from a
MySQL database using Hibernate. As of this document the version of Flex is Beta 2 and BlazeDS nightly build http://flexorg.wip3.adobe.com/blazeds ... ds-turnkey-3.2.0.3978.zip

The following software is required for this Tutorial:

1. Adobe Flash Builder 4 (60 day trial) http://labs.adobe.com/technologies/flashbuilder4/
2. BlazeDS turnkey (includes Tomcat)
http://flexorg.wip3.adobe.com/blazeds ... ds-turnkey-3.2.0.3978.zip

3. Hibernate Core http://www.hibernate.org
a. hibernate-annotations-3.4.0.GA
b. hibernate-distribution-3.3.2.GA-dist (Core)
c. hibernate-entitymanager-3.4.0.GA
d. hibernate-validator-4.0.2.GA-dist
4. Mysql Community Database http://dev.mysql.com/downloads/
5. MySQL GUI Tools http://dev.mysql.com/downloads/workbench/5.2.html
6. Log4J http://logging.apache.org/log4j/1.2/index.html
7. Simple Logging Facade for Java (SLF4J) http://www.slf4j.org/
8. Eclipse IDE http://www.eclipse.org/
9. MySQL JDBC Connector http://www.mysql.com/products/connector/
10. Apache Common Language 2.x http://commons.apache.org/lang/
11. Java JDK 1.6 http://java.sun.com/javase/downloads/index.jsp

In this tutorial I use both Flash Builder 4.0 and Eclipse 3.4 as separate IDE’s you can download Adobe Flash Builder 4 plug-in for Eclipse. In most cases separatation of development will be performed by different developers and so in this tutorial I have separated the Java developers from the Flex developers.

• Install Java JDK 1.6
• Install MySQL server
• MySQL GUI tools.


Configure System Variables

To configure the JDK home etc you will need to add System Variables for Windows Vista this
will be completed in the Control Panel ==> System




Double Click on the System Icon



Select Advanced system Settings



Select Environment Variables button



Select New and create the following System Variables:

1. JAVA_HOME The full path to where you installed the JDK
2. JRE_HOME (i.e. C:\Program Files\Java\jdk1.6.0_13\jre)
3. TOMCAT_HOME (C:\blazeds\tomcat)
4. Click ok when all done and re-boot computer


Begin by Installing Eclipse & Flash Builder 4.0 in the case of Eclipse you extract the zip file to your C:\. Run the installer for Flash Builder 4 everything will be handled by the installer nothing
special required in these installations.

Once the above has been completed we will now install BlazeDS Server (this example uses Windows Vista)

Download BlazeDS from: http://opensource.adobe.com/wiki/display/blazeds/BlazeDS in this build I notice a jar was missing flex-rds-server.jar which is very important. If this jar is not in the lib directory download the latest binary and extract from the blazeds.war file and place in the C:\blazeds\tomcat\webapps\blazeds\WEB-INF\lib



Extract BlazeDS zip file to C:\blazeds


Configure BlazeDS

In this section we will configure BlazeDS for our Flex project. We first need to setup a directory under Tomcat webapps to be recognized by the Flash Builder 4. Under C:\blazeds\tomcat\webapps create a new folder called HibDemo

Next we will need some basic configurations provided by BlazeDS so copy
C:\blazeds\tomcat\webapps\blazeds\WEB-INF to
C:\blazeds\tomcat\webapps\HibDemo

Remove the following directory:

1.Src

You should now have the following 3 folders and web.xml file:






BlazeDS RDSDispatchServlet

There are a couple of xml files we need to configure for our demo application first is the Web.xml. By default the RDSDispatchServlet is disabled by default in order to enable this copy the below text to the web.xml
(Thanks to this blog:Sujit Reddy G – The Evangelist)



<servlet>
<
servlet-name>RDSDispatchServlet</servlet-name>
<
display-name>RDSDispatchServlet</display-name>
<
servlet-class>flex.rds.server.servlet.FrontEndServlet</servlet-class>
<
init-param>
<
param-name>useAppserverSecurity</param-name>
<
param-value>false</param-value>
</
init-param>
<
load-on-startup>10</load-on-startup>
</
servlet>
<
servlet-mapping id=”RDS_DISPATCH_MAPPING”>
<
servlet-name>RDSDispatchServlet</servlet-name>
<
url-pattern>/CFIDE/main/ide.cfm</url-pattern>
</
servlet-mapping>


Note: One thing I noticed about copying text from Microsoft Word to an XML file is the double quotes get messed up. Make sure you delete the “ and re-add around the otherwise BlazeDS will complain about invalid text.

The next XML file to edit is under C:\blazeds\tomcat\webapps\HibDemo\WEB-INF\flex called
remoting-config.xml this is where we set the Destination for our service which Flex uses for connection.


The remoting-config.xml file :
<destination id="DemoSampleDestination" channels="my-amf">
<
properties>
        <
source>com.dcostelloe.demo.ListAllusers</source>
    </
properties>
</
destination>


The completed remoting-config.xml file :
<?xml version="1.0" encoding="UTF-8"?>
<service id="remoting-service" 
    class="flex.messaging.services.RemotingService">
    <adapters>
        <adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter" default="true"/>
    </adapters>
<destination id="DemoSampleDestination" channels="my-amf">
    <properties>
        <source>com.dcostelloe.demo.ListAllusers</source>
    </properties>
</destination>


In this file we set the destination name for the service, this name will be used by Flash Builder 4 when connection to BlazeDS server. The prop erty section is the package name and name of the Java Class.

Flash Builder to correctly pick up the service as we will see later in the Flex Builder project.


MySQL Database Configuration

Now we will create a simple database and table to read using Hibernate and Java. Open the MySQL Query Browser part of the MySQL GUI tools installed.



Enter the root password you setup during installation and click OK




Right click the Schema Tab and select Create New Schema (CTRL-N)



Enter DemoSample as the name and click OK:



Right Click DemoSample Schema and select create Table:



Create the following table and Fields:



Make sure user_id is primary key and Auto Increment.



Click Execute.



Insert the following records:

INSERT INTO userlist 
(user_login,user_passwordVALUES ('David Welford-Costelloe','david');
INSERT INTO userlist (user_login,user_passwordVALUES ('Doug Pile','doug');
INSERT INTO userlist (user_login,user_passwordVALUES ('Bob Hope','bhope');


Sample after insertion:



Building Java Classes

This section we will be working with Eclipse (Java developer) to create the required Java classes to access the database using Hibernate.
Create New Java Project File ==> New ==> Java Project use the JDK 1.6 as below:





Create a New Java Package: Right click the src folder and select New ==> Package

Add name as com.dcostelloe.demo and click Finish





Right click the com.dcostelloe.demo package and select New ==> Class Enter name as Users and click on the Add Interfaces enter ‘ser’ and select the Serializable ==> java.io and click Add and then OK




Once completed you should have a class created with the following:



Click Finish to create Class

Add the following to the User Class


private   int   userId  0
private  
String  loginName  =  null 
private  
String  loginPassword  =  null 


Generate Getters/Setters for each of the above:



Right Click userId and select Generate Getters/Setters



Use the configuration as below and click OK:



All Getters/Setters will be generated for you:



These are the properties for each column in the UserList table we will be accessing using Hibernate and MySQL.

Now we will create the Hibernate configuration files, these are a set of XML files that are
required by Hibernate. Add a new folder called cfg to the project.
Right Click the cfg folder and create th e following x ml.properties files:
1. hibernate.cfg.xml
2. Users.hbm.xml
3. log4j.properties


Once completed we need to add the cfg to the build path: Right Click the project and select properties.




Click Add Class Folder and select cfg folder from project:



Click ok to complete



Click ok once you see the cfg folder, this is to ensure that Hibernate can find the configuration files when you execute the application.

Next we need to add the third party jar files to the lib folder of the project:
Add a new folder to the project called lib from the downloaded Hibernate.Log4J and MySQL JDBC driver add the following jars from each to the project lib directory:

a) mysql-connector-java-5.1.10-bin.jar
b) All of the jars in: \hibernate-distribution\lib\required (Where you unzipped hibernate)
c) hibernate3.jar from \hibernate-distribution
d) slf4j-api-1.5.10.jar \slf4j-1.5.10 (remove lower v ersion if there)
e) slf4j-log4j12-1.5.10.jar \slf4j-1.5.10
f) log4j-1.2.15.jar from \apache-log4j-1.2.15




Use import from File Menu



Click Next

Browse to the folders (do the same procedure for each jar file) and click finished. Add all of the
below to the lib folder:




Note: we will also need to copy these jars to the BlazeDS lib folder which we will do later in the document.


Hibernate Configuration Files

Now we will create the required files for Hibernate usage as defined earlier.

Here is the content for each File:


Hibernate.cfg.xml

 
<? xml   version "1.0"   encoding "UTF-8" ?>  
<! DOCTYPE   hibernate-configuration   PUBLIC   "-//Hibernate/Hibernate Configuration DTD 3.0//EN"   "http://hibernate.sourceforge.net/hibernate-
configuration-3.0.dtd">  
 <hibernate-configuration>  
      <session-factory>  
                <!-- Data Connection Settings -->      
               <property name = "connection.driver_class" >com.mysql.jdbc.Driver </property>  
               <property name = "connection.url">jdbc:mysql://localhost:3306/demosample</property>  
               <property name = "connection.username">root</property>  
               <property name = "connection.password">dbpassword</property>    
                    <!-- SQL Dialect -->  
                <property name = "dialect">org.hibernate.dialect.MySQLDialect</property>  
                      <!-- Hibernate session -->  
               <property name = "current_session_context_class">thread</property>  
                    <!--  Write SQL to log or console -->       
               <property name = "show_sql">true</property>  
                <!-- Mapping Files -->  
                 <mapping resource = "Users.hbm.xml"/>  
     </session-factory>    
   
</hibernate-configuration>


Log4j.properties

 
log4j
.appender.stdoutorg.apache.log4j.ConsoleAppender     
log4j
.appender.stdout.layout=org.apache.log4j.PatternLayout     
   
log4j
.rootLoggerdebug,stdout  
   
log4j
.logger.org.hibernateerror  
log4j
.logger.org.hibernate.SQL=error  
 
log4j
.logger.org.hibernate.type=error  
log4j
.logger.org.hibernate.cache=error


Users.hbm.xml

 
<? xml version "1.0" encoding "UTF-8" ?>  
<! DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
   <hibernate-mapping>  
      <class name = "com.dcostelloe.demo.Users" table = "USERLIST">  
               <id name = "userId" column = "user_id" type= "java.lang.Integer">    
                        <generator class = "increment"/>  
               </id>  
                <property name = "loginName" column = "user_login" type = "java.lang.String"/>  
                 <property name = "loginPassword" column= "user_password" type = "java.lang.String"/>  
     </class>  
</hibernate-mapping>


ListAllUsers Java Class

 
package com
.dcostelloe.demo
import java.util.List; 
import org.apache.commons.lang.StringUtils
import org.hibernate.HibernateException;   
import org.hibernate.SessionFactory
import org.hibernate.Transaction;   
import org.hibernate.cfg.Configuration
import org.hibernate.classic.Session
 
import org.hibernate.criterion.Restrictions
 
/** 
 * @author David Welford-Costelloe 
   * 
 */ 
 
public class ListAllUsers 
 
  @
SuppressWarnings("unchecked")  
  public List<
UsersgetUserList(S tring sUserString sPassword
    { 
    List<
UsersallUsers null;     
 
    try { 
      
//Set up Hibernate Session   
      
Configuration config = new Configuration(); 
      
config.configure("hibernate.cfg.xml"); 
 
      
SessionFactory sessionFactory config.buildSessionF actory(); 
                    
Session session sessionFactory.getCurrentSession(); 
 
      @
SuppressWarnings("unused"
        
Transaction tx session.beginTransaction();       

// I like to use apache Common Language    
if (StringUtils.isBlank(sUser)) 

 
       
// If null passed return all records 
       
allUsers session.createCriteria(Users.class).list(); 
 
      } 
        Else 
      { 
                                           
// Use Property not column names   
        
allUsers 
session.createCriteria(Users.class).add(Restrictions.eq("loginName",sUser)).add(Restrictions.eq("loginP assword",   
sP assword)).list(); 
      } 
 
    } catch (
HibernateException e) { 
 
      
e.printStackTra ce(); 
    }   

    return 
allUsers
  } 



This class will make a call to Hibernate and return all or a single record based upon the criteria, as Flash builder 4 allows you to test your service connection I added the option to return a specific record by using Hibernate session.createCriteria method, this method acts similar to a SQL WHERE clause. This class does not contain much code but will provide code reusability.
If you look at the right of the image below I have created a test case for this class in the Flash Builder 4.




Test Java Class
This class I created for the sole purpose of testing my connection without using BlazeDS going
directly using a Java call to Hibernate from the Eclipse IDE. You will find this code in the provided source code.




Hibernate Java Results
As you can see from the below image if all is well with your configurations and classes you can run the Test java class and get back results.



Flex Builder Application
The next step is to create a Flex web application to connect to BlazeDS and execute java classes in order to return the list of Users.



Start the Flash Builder 4:



Create a new Flex Builder Project:



Use the below settings to create the project



Click Validate Configuration



Click Finish once configuration has been Validated.



Click Finish




Connecting to BlazeDS

Now we need to deploy our classes and configuration files to the BlazeDS server:
1. Copy the class files
a. ListAllUsers.class
b. Users.class
c. Copy library files to BlazeDS
C:\blazeds\tomcat\webapps\HibDemo\WEB-
INF\lib\

2. Right Click the Eclipse project in the Navigation menu bin com folder and select Copy from the menu





3. Copy the complete com folder to C:\blazeds\tomcat\webapps\HibDemo\WEB-INF\classes
4. Delete the Test folder:
C:\blazeds\tomcat\webapps\HibDemo\WEB-INF\classes\com\dcostelloe\demo
5. Copy the configuration files from the cfg folder:
a. hibernate.cfg.xml
b. log4j.properties
c. Users.hbm.xml
6. To: C:\blazeds\tomcat\webapps\HibDemo\WEB-INF\classes




7. Start the BlazeDS server by going to the folder: C:\blazeds\tomcat\bin and double clicking on: startup.bat
If all is configured as expected you will see the following console




Flash Builder 6 has an nice new feature called Data-Centric Development; this is what we will use for this demo.




1. Open the DemoSample.mxml in Design Mode and drag and drop a DataGrid.



2. Create a connection to the BlazeDS server: from the Data Menu select Con nect to Data/Service



3. Select BlazeDS and click Next



4. Select the Destination as per below (If you do not see a destination check the remote-config.xml on the BlazeDS Server.




5. Check the box next to DemoSampleDestination

6. Click Finish to build the code

7. Set the Datagrid width & height to 100%

8. Refresh the grid




9. Right Click anywhere on the DataGrid and select Bind to Data



10. Select New Service and select the destination of DemoSampleDestination the operation is getUserList




11. Click Ok when selected same as above
12. Change the code highlighted add null,null


getUserListResult3
.token demoSampleDestination.getUserList(null,null);  







13. And that is it you can now run the application in Flash 4 Builder and return the results from the database using Hibernate. Code is completed for you by Flash Builder 4. If you have configured everything correctly you can see the results in the Datagrid.



Congratulations on your new BlazeDS/Hibernate/MySQL connection using Flex 4. Please feel free to contact me should you need assistance on this web site.

Test Source Code

Due to popular demand I have added the test code for the direct to Hibernate source below.


/** 
 *  
 */ 
package com.ca.on.burlington.demo.test

import java.util.List; 

import com.ca.on.burlington.demo.ListAllUsers
import com.ca.on.burlington.demo.Users

/** 
 * @author David Welford-Costelloe 
 * 
 */ 
public class TestMySQL 

    
/** 
     *  
     */ 
    
public TestMySQL() { 
        
// TODO Auto-generated constructor stub 
    


    
/** 
     * @param args 
     */ 
    
public static void main(String[] args) { 
        
// TODO Auto-generated method stub 
        
ListAllUsers listU = new ListAllUsers(); 
         
        
// Uncomment to get one record 
        //String sUser = "David Welford-Costelloe"; 
        //String sPassword = "david"; 
        // List<Users> allUsers =     listU.getUserList(sUser, sPassword); 
        // Get all records 
        
List<UsersallUsers =     listU.getUserList(nullnull); 
         
        for (
Users s allUsers) { 
            
System.out.println("User ID     : [" s.getUserId() + "]\n" "Login Name   : [" s.getLoginName() + "]\n" "Password    : [" s.getLoginPassword() + "]" ); 

        } 
    } 

Read Admin's weBLog | Comments (3) | Trackback (1) | Reads (219)
Trackback URL of this entry
http://welford-costelloe.com/modules/weblog/weblog-tb.php/10
Trackbacks to this entry
2010-08-25/13:04:28
Printer Friendly Page Send this Blog to a Friend
The comments are owned by the poster. We aren't responsible for their content.

Poster Thread
berkayk
Posted: 2010/8/14 14:46  Updated: 2010/8/14 14:46
Just popping in
Joined: 2010/8/14
From: Istanbul
Posts: 1
 Source Code?
Hi, thanks for this amazing tutorial. I have a question though. In the section where you explain Test Class,

"This class I created for the sole purpose of testing my connection without using BlazeDS going
directly using a Java call to Hibernate from the Eclipse IDE. You will find this code in the provided source code."

I couldn't find the link for the source code. I'm stuck at that step :)

Thanks.

Poster Thread
Admin
Posted: 2010/8/15 9:45  Updated: 2010/8/15 9:45
Webmaster
Joined: 2010/5/5
From: Burlington Ontario Canada
Posts: 204
 Re: Source Code?
Hi,
You can download the source code for all tutorials from the Download Section on the Navigation Bar on the left or use this link when logged in:
http://www.welford-costelloe.com/modu ... nloads/viewcat.php?cid=11

Thanks for your comments very much appreciated.

David........

Poster Thread
Admin
Posted: 2010/8/16 12:14  Updated: 2010/8/16 12:14
Webmaster
Joined: 2010/5/5
From: Burlington Ontario Canada
Posts: 204
 Re: Source Code?
Here is the Test code

/**
 * 
 */
package com.ca.on.burlington.demo.test;

import java.util.List;

import com.ca.on.burlington.demo.ListAllUsers;
import com.ca.on.burlington.demo.Users;

/**
 * @author David Welford-Costelloe
 *
 */
public class TestMySQL {

    
/**
     * 
     */
    
public TestMySQL() {
        
// TODO Auto-generated constructor stub
    
}

    
/**
     * @param args
     */
    
public static void main(String[] args) {
        
// TODO Auto-generated method stub
        
ListAllUsers listU = new ListAllUsers();
        
        
// Uncomment to get one record
        //String sUser = "David Welford-Costelloe";
        //String sPassword = "david";
        // List<Users> allUsers =     listU.getUserList(sUser, sPassword);
        // Get all records
        
List<UsersallUsers =     listU.getUserList(nullnull);
        
        for (
Users s allUsers) {
            
System.out.println("User ID     : [" s.getUserId() + "]\n" "Login Name   : [" s.getLoginName() + "]\n" "Password    : [" s.getLoginPassword() + "]" );

        }
    }
}
Powered by XOOPS @ 2001-2010 The XOOPS Project