Anonymous,

Please Login or Register
Download Nuke Evolution today for a CMS you can enjoy using and sharing with your friends!

[ Download Now ]
Main Menu   
 
HomeHome  
    Home
Members  
    Profile
    Your Account
Community  
    Forums
Statistics  
    Statistics
    Top 10
Files & Links  
    Downloads
News  
    News
Other  
    Tutorials
    Content
    FAQ
    Site Map
Search   
 


Tutorials: FlashBuilder Sample Using BlazeDs 4, Java, Hibernate and MySQL


Description:

This document takes you through the complete setup of Flex 4 to get data from a MySQL database using Hibernate. As of this document the version of Flex is version 4 and BlazeDS 4


Version: 1.0
Added on: 28 May 2011
Author: David Welford-Costelloe
Difficulty Level: Easy
Views: 898
Rating: 9.0 (1 Vote)
Detailed Profile
Rate Resource

FlashBuilder Sample Using BlazeDs 4, Java, Hibernate and MySQL


This document takes you through the complete setup of Flex 4 to get data from a MySQL database using Hibernate. As of this document the version of Flex is version 4 and BlazeDS 4: http://opensource.adobe.com/wiki/display/blazeds/Downloads

The following software is required for this Tutorial:




1. Adobe Flash Builder 4 (60 day trial) http://tryit.adobe.com/us/flashbuilder/?sdid=FDPUB

2. BlazeDS turnkey (includes Tomcat)

http://opensource.adobe.com/wiki/display/blazeds/Downloads



3. Hibernate Core http://www.hibernate.org

a. hibernate-distribution-3.5.4-Final-dist

b. hibernate-validator-4.1.0.Final-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 http://www.oracle.com/technetwork/java/javase/downloads/index.html



In this Tutorial I use both Flash Builder 4.0 and Eclipse as separate IDE’s you can download Adobe Flash Builder 4 plug-in for Eclipse. In most cases separation 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


Open in new window







Double Click on the System Icon

Open in new window







Select Advanced system Settings

Open in new window







Select Environment Variables button

Open in new window







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 FilesJavajdk1.6.0_13jre)

3. TOMCAT_HOME (C:lazeds omcat)

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 for Windows Vista or Windows 7)



Download BlazeDS from:
http://opensource.adobe.com/wiki/display/blazeds/Downloads



Open in new window





Extract BlazeDS zip file to C:lazeds



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:lazeds omcatwebapps create a new folder called HibDemo



Next we will need some basic configurations provided by BlazeDS so copy

C:lazeds omcatwebappslazedsWEB-INF to

C:lazeds omcatwebappsHibDemo



Remove the following directory under WEB-INF



1.Src



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




Open in new window





Open in new window





Open in new window







BlazeDS RDSDispatchServlet



There are a couple of xml files we need to configure for our tutorial application first is the Web.xml. By default the RDSDispatchServlet is commented out by default in order to enable this; uncomment the section in the web.xml




Open in new window





Edit the web.xml in the HibDemoWEB-INF

Change the <param-value> and set this to false:





<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>






Open in new window





Save the web.xml



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:lazeds omcatwebappsHibDemoWEB-INFflex called remoting-config.xml this is where we set the Destination for our service which Flex uses for connection.

Add the following:







<destination id="HibDemoDestination" channels="my-amf">

<
properties>

        <
source>com.ca.on.burlington.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="HibDemoDestination" channels="my-amf">

    <properties>

        <source>com.ca.on.burlington.demo.ListAllusers</source>

    </properties>

</destination>

    <default-channels>

        <channel ref="my-amf"/>

    </default-channels>



</service>






In this file we set the destination name for the service, this name will be used by Flash Builder 4 when connecting to BlazeDS server. The property 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.



Open in new window







Open in new window







Click on “New Connection”

Open in new window





On the Setup New Connection Add a Connection Name, this can be anything you want and then click on “Store in Vault” button

Open in new window





Open in new window







Enter the password entered on installation of MySQL Database Server and click OK

Open in new window







Click on “Test Connection” and you should see

Open in new window







Click OK

Open in new window







Double Click on the connection you created in the “Open Connection to start Querying”

Open in new window







Right click anywhere on the left Window Pane and select “create schema”

Open in new window





Enter the name as “demosample” (without quotes)

Open in new window





Click on Apply button

Open in new window





Click Apply SQL Button and then Finish button and then close button

Open in new window





In the object browser select the demosample schema and right click on the Table folder and select Create Table



Open in new window







Name the table as: userlist



Open in new window





Click on Columns Tab on lower area

Open in new window





Add the following Columns:







Column Name    DataType    PK    NN    BTN    UN    ZF    AI    Default

User_id        INT         Y      Y     N     N      N      Y    

User_login    VARCHAR
(45)                    

User_password    VARCHAR(45)






Open in new window







Click Apply button



Open in new window





Click Apply SQL button

Open in new window







Click on Finish button and then Close



Open in new window





You can now see the table listed as per above



Open in new window







Select from the Object Browser dropdown the schema demosample



Next we need to add some records using the below add at least 3 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');






Copy the above script to the SQL Query Window



Open in new window





Then click on the Open in new window

on the toolbar




Open in new window







As per above the 3 records have been inserted into the demosample schema



Sample after insertion:




Open in new window







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:




Open in new window





Click Finish Button





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



Add name as com.ca.on.burlington.demo and click Finish




Open in new window





Right click the com.ca.on.burlington.demo package and select New ==> Class Enter name as Users



Open in new window





click on the Add Interfaces enter ‘ser’ and select the Serializable ==> java.io and click Add and then OK



Open in new window





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



Open in new window





Click Finish to create Class



Add the following to the User Class







private   int   userId  0;  

private  
String  loginName  =  null ;  

private  
String  loginPassword  =  null 







Open in new window





Generate Getters/Setters for each of the above:

Open in new window





Right Click userId and select Generate Getters/Setters

Open in new window





Use the configuration as below and click OK and Save



Open in new window





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.




Open in new window





Open in new window





Right Click the cfg folder and create the following xml.properties files:



Open in new window





Select Other and scroll down to the XML Folder



Open in new window





Select XML and click Next Button. We are going to need 2 XML files so create the other two in the same fashion



1. hibernate.cfg.xml

2. Users.hbm.xml

3. log4j.properties (This is a text file)




Open in new window





Click on Finish Button. Next we create the properties file



Open in new window





Add any text at this point



Open in new window





Click on save from Menu Open in new window

and Name this file as log4j.properties in the DemoDataService/cfg folder




Open in new window





Click Ok



Open in new window





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

Open in new window





Select Java Build Path



Open in new window





Click Add Class Folder and select cfg folder from project:

Open in new window





Click ok to complete



Open in new window





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-?.?.??-bin.jar

b) All of the jars in: hibernate-distributionlib equired (Where you unzipped hibernate)

c) hibernate3.jar from hibernate-distribution

d) slf4j-api-?.?.??.jar slf4j-?.?.?? (remove lower version if there)

e) slf4j-log4j??-?.?.??.jar slf4j-?.?.??

f) log4j-?.?.??.jar from apache-log4j-?.?.??




Use import from File Menu



Open in new window





Open in new window





Click Next and select the directory you have extracted the mysql-connector



Open in new window





Click OK and add /lib to the Into Folder: DemoDataService/lib



Open in new window





Click Finished



Open in new window





Open in new window







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



Open in new window





Next we need to add these jars to the Build Path in Eclipse



Open in new window





Right click project DemoDataService and select Properties



Open in new window





Select Java Build Path from the left and then click on Add JARS.. button



Open in new window





Select all jars in the lib folder and click OK



Open in new window





Click OK



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



Open in new window





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">YourRootPassword</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.rootLogger=debug,stdoutR



log4j
.appender.stdout=org.apache.log4j.ConsoleAppender

log4j
.appender.stdout.layout=org.apache.log4j.PatternLayout



log4j
.logger.org.hibernateerror   

log4j
.logger.org.hibernate.SQL=error   

  

log4j
.logger.org.hibernate.type=error   

log4j
.logger.org.hibernate.cache=error



# Pattern to output the caller's file name and line number.

log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n



log4j
.appender.R=org.apache.log4j.RollingFileAppender

log4j
.appender.R.File=DemoSample.log



log4j
.appender.R.MaxFileSize=100KB

# Keep one backup file

log4j.appender.R.MaxBackupIndex=1



log4j
.appender.R.layout=org.apache.log4j.PatternLayout

log4j
.appender.R.layout.ConversionPattern=%%%- %m%n







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.ca.on.burlington.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.ca.on.burlington.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 {



    
/**

     * 

     */

    
public ListAllUsers() {

        
// TODO Auto-generated constructor stub

    
}

    

    @
SuppressWarnings("unchecked")

    public List<
UsersgetUserList(String sUserString sPassword)  

    {  

    List<
UsersallUsers null;      

  

    try {  

      
//Set up Hibernate Session    

      
Configuration config = new Configuration();  

      
config.configure("hibernate.cfg.xml");  

  

      
SessionFactory sessionFactory config.buildSessionFactory();  

                    
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("loginPassword",sPassword)).list();  

      }  

  

    } catch (
HibernateException e) {  

  

      
e.printStackTrace();  

    }    



    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.




Open in new window





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.



Open in new window





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.



Open in new window







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:



Open in new window





Click on Start Trial



Open in new window





Enter you adobe login information used to download Flash Builder and click Next

Open in new window





Click on Done



Open in new window





Open in new window





Create a new Flex Builder Project:



Open in new window





Open in new window





Use the below settings to create the project. Project Name DemoSampleFlex in the Server technology select J2EE and check Use Remote object access service and Check BlazeDS

Open in new window





Click Next

Enter Root Folder Browse to BlazeDS and select the HibDemo folder under tomcatwebapps

Root URL will be the default of BlazeDS port of 8400: http://localhost:8400/HibDemo

Context Root: /HibDemo




Click Validate Configuration



Open in new window





As you can see the message being returned from the Validate Configuration states cannot access the web server. This is because I have not started BlazeDS server. Click Next



Open in new window





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 lib folder jar library files to BlazeDS

C:lazeds omcatwebappsHibDemoWEB-INFlib




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




Open in new window





3. Copy the complete com folder to C:lazeds omcatwebappsHibDemoWEB-INFclasses



Open in new window





4. Delete the Test folder:

Open in new window





C:Usersdavidlazeds omcatwebappsHibDemoWEB-INFclassescomcaonurlingtondemo



5. Copy the below files:

a. hibernate.cfg.xml

b. log4j.properties

c. Users.hbm.xml

6. To: C:lazeds omcatwebappsHibDemoWEB-INFclasses




Open in new window





Important : Make sure you copy the jars in the Eclipse lib directory to C:Usersdavidlazeds omcatwebappsHibDemoWEB-INFlib



Open in new window





7. Start the BlazeDS server by going to the folder: C:lazeds omcatin and running: startup.bat



Open in new window





If all is configured as expected you will see the following console



Open in new window





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



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




Open in new window





Open in new window





On the Menu select Data and then Connect to BlazeDS



Open in new window





Check the box No Password Required (remember earlier we set this to false)



Open in new window





Click OK



Open in new window





If you get this error from FlashBuilder shutdown BlazeDS and edit the web.xml. Remove <!-- begin rds and end rds --> to uncomment the









<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>






Startup BlazeDS again



Select Data on menu again and select HibDemoDestination




Open in new window





Click Finish



You will see the following



Open in new window





Next we will setup a test for the connection:



Open in new window





Right Click in the lower Data/Services and getUserList and select Test Operation



Check the left window and add parameters




Open in new window





Click Test to see the above results



Next we will set the DataGrid to fill the page click on left Tab screen and select properties

Open in new window





7. Set the Datagrid width & height to 100% or change this code







<mx:DataGrid width="100%" height="100%">






8. Refresh the grid



Open in new window





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



Open in new window





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

Open in new window





11. Click Ok when selected same as above

12. Change the code highlighted add null,null





getUserListResult.token hibDemoDestination.getUserList(/*Enter value(s) for */ arg0arg1);




to:



getUserListResult.token hibDemoDestination.getUserList(nullnull);






Open in new window





Open in new window





Select from the Menu Open in new window

arrow

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.




Open in new window







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. enlightened

Tutorials ©