Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

hibernate

  • submit to reddit

Daily Dose: Windows Phone gets a New App Hub

Microsoft announced a new hub for Windows Phone developers today, called the "App Hub". The new marketplace will feature geographic markets, options for privately distributing your applications, and better application and account management...

0 replies - 17323 views - 07/21/11 by Ross Jernigan in Daily Dose

Daily Dose: Hibernate Search 3.4 Upgrades to Lucene 3.1

Hibernate 3.4 has several notable new features, including an upgrade to the new Lucene 3.1.  The focus of this release was improved faceting.  By dividing the results of each query into multiple categories, determining the number of matching elements with...

1 replies - 23335 views - 04/19/11 by Katie Mckinsey in Daily Dose

Daily Dose - NoSQLs Join Forces

NoSQL backers Membase and CouchOne just announced that they are merging to create Couchbase, Inc.  Combining the caching and clustering technology of Membase, and the document database capabilities of CouchDB, the newly-minted Couchbase company will be...

0 replies - 18218 views - 02/09/11 by Katie Mckinsey in Daily Dose

Daily Dose - Oracle to Sell "Premium" JVM

Tweets coming out of the weekend's QCon conference revealed Oracle's plan for a premium JVM that comes with a price tag.  Adam Messinger, the Oracle VP of development made the announcement saying that Oracle still plans to develop a free and open source...

3 replies - 20444 views - 11/08/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - GAE Gets New Admin Utilities

Google released the next version of the Google AppEngineSDK this week.  The new 1.3.8 SDK includes a new Admin Console called the Instances page, which lets you see information on all server instances that an application is using.  There are also new task...

0 replies - 16969 views - 10/16/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Go to the 'Go Playground'

Google's golang.org website for exploring their new programming language now includes a new feature called the Go Playground.  The Playground allows anyone to write code in Go that can be immediately compiled, linked, and deployed on Google's servers.  The...

0 replies - 16570 views - 09/17/10 by Mitchell Pronsc... in Daily Dose

DZone Daily Dose - Hibernate 3.5.5 Deprecates CGLIB Support

A decent amount of uproar was generated this week when JBoss developers indicated that the latest stable release of Hibernate (3.5.5) would have deprecated support for CGLIB as a bytecode provider.  Developers can still use CGLIB as the bytecode provider,...

1 replies - 24767 views - 08/21/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Meerkat Becoming More 'Mavericky'

The third alpha release of Ubuntu 10.10 "Maverick Meerkat" is upon us.  Based on the 2.6.35 Linux kernel, Ubuntu 10.10 a3 has updated to GNOME 2.31 and the Qt 4.7 beta.  The software center has gotten a 'featured' and 'what's new' carousel in the...

0 replies - 13591 views - 08/06/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Hibernate 3.5.4 and 3.6 Beta 1 Released in Tandem

JBoss delivered the final version of its Hibernate 3.5.4 maintenance release this week along with the first beta of 3.6, which adds some new features.  First of all, 3.6 will drop support for JDK 1.4.  It will also merge some modules into the core...

1 replies - 13652 views - 07/23/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Hibernate and Hibernate Validator Releases

The final release of Hibernate 3.5.3 was delivered today with three main bugfixes.  Hibernate Validator 4.1 CR 1 was also released today.  Validator 4.1 adds new custom constraints, provides enhancement which go beyond the Bean Validation specification, and...

0 replies - 13236 views - 06/18/10 by Mitchell Pronsc... in Daily Dose

Flex 4 and Spring 3 Integration

By Jon Rose and James Ward

13,520 Downloads · Refcard 102 of 151 (see them all)

Download
FREE PDF


The Essential Flex 4 and Spring 3 Cheat Sheet

Flex 4 and Spring 3 Integration: Adobe Flex has strong ties to Java, which include an Eclipse-based IDE and BlazeDS, its open source server-based Java remoting and web messaging technology. In this DZone Refcard, you will learn how to use Flex Remoting and Messaging to connect to Spring and Hibernate. Also included is a section on how to use Spring Security with Flex. This tutorial assumes that you are already familiar with Spring and Flex. If you need an introduction or refresher to either, check out the Very First Steps in Flex and Spring Configuration DZone Refcardz.
HTML Preview
Flex 4 & Spring 3 Integration

Flex 4 & Spring 3 Integration

By Jon Rose and James Ward

INTEGRATING FLEX AND SPRING

Adobe Flex has strong ties to Java, which include an Eclipse-based IDE and BlazeDS, its open source server-based Java remoting and web messaging technology. In late 2008, the Spring community began working on the Spring BlazeDS Integration project to add support for Flex development with Java and Spring.

By default BlazeDS creates instances of server-side Java objects and uses them to fulfill remote object requests. This approach doesn’t work with Spring, as the framework is built around injecting the service beans through the Spring container. The Spring integration with BlazeDS allows you to configure Spring beans as BlazeDS destinations for use as remote objects in Flex.

This tutorial assumes that you are already familiar with Spring and Flex. If you need an introduction or refresher to either, check out the Very First Steps in Flex and Spring Configuration DZone Refcardz.

Hot Tip

BlazeDS provides simple two-way communication with Java back ends. Flash Player supports a serialization protocol called AMF that alleviates the bottlenecks of text-based protocols and provides a simpler way to communicate with servers. AMF is a binary protocol for exchanging data that can be used over HTTP in place of text-based protocols that transmit XML. Applications using AMF can eliminate an unnecessary data abstraction layer and communicate more efficiently with servers. To see a demonstration of the performance advantages of AMF, see the Census RIA Benchmark at: http://www.jamesward.org/census

To follow along with this tutorial you will initially need:

  • An Eclipse 3.5 Distribution. You may choose either the standard distribution: Eclipse 3.5 (Galileo) for Java EE Developers (On Mac use the Eclipse Carbon version): http://www.eclipse.org/downloads/ Or, for enhanced Spring support you might consider using the SpringSource Tool Suite:

http://www.springsource.com/products/springsource-tool-suite-download/

Manually downloading the dependencies is one way to get everything you need. Alternatively, you can use Maven or the SpringSource Tool Suite to automatically handle dependencies for you.

First install your chosen Eclipse distribution and then install Flash Builder 4 as a plug-in to the Eclipse distribution you just installed. Also extract the ZIP files for the other dependencies specified above. When you’ve completed these steps, run Eclipse. In Eclipse create a server that will run the application:

  1. Choose File > New > Other
  2. Select Server > Server
  3. Click Next
  4. Select Apache > Tomcat v6.0 Server
  5. Click Next
  6. Specify the location where Tomcat is installed and select the JRE(version 5 or higher) to use
  7. Click Finish

There are two ways to begin setting up the Dynamic Web project in Eclipse. You can either start with a prepackaged project containing all of the dependencies or you can start from scratch and configure everything by hand. Starting from scratch will help you to better understand how everything fits together, however it will take a little bit more time to download all of the dependencies and configure Spring and BlazeDS.

To begin with the prepackaged project, download this project archive:
http://static.springsource.org/spring-flex/refcard/flexspring-refcard_justdeps.zip

Then, in Eclipse select File > Import and select the Existing Projects Into Workspace option. Using the Select Archive File option and Browse button, locate the flexspring.zip file, and then click Finish.

Alternatively to start from scratch, set up the server-side Java web project in Eclipse by creating a web application from the blazeds.war file (found inside the BlazeDS zip file).

In Eclipse, import the blazeds.war file to create the project:

  1. Choose File > Import
  2. Select the WAR file option. Specify the location of the blazeds.war file.For the name of the web project, type flexspring
  3. Click Finish

First remove the xalan.jar file from the WebContent/WEB-INF/lib folder. Next, go into the project properties. One way to get there is by right-clicking on the project and selecting Properties. In the project properties, select Java Build Path and then click the Source tab. Set the Default Output Folder to be the following (you will need to create the classes folder):


flexspring/WebContent/WEB-INF/classes

This causes all Java classes that are created in the project to be deployed in the web application.

In the WebContent/WEB-INF/flex folder update the services-config.xml file with the following contents:


<?xml version=”1.0” encoding=”UTF-8”?>
<services-config>
  <channels>
    <channel-definition id=”my-amf” class=”mx.messaging.channels.AMFChannel”>
       <endpoint url=”http://{server.name}:{server.port}/{context.root}/messagebroker/amf” class=”flex.messaging.endpoints.AMFEndpoint”/>
    </channel-definition>
    <channel-definition id=”my-streaming-amf” class=”mx.messaging.channels.StreamingAMFChannel”>
       <endpoint url=”http://{server.name}:{server.port}/{context.root}/messagebroker/streamingamf” class=”flex.messaging.endpoints.StreamingAMFEndpoint”/>
    </channel-definition>
    <channel-definition id=”my-polling-amf” class=”mx.messaging.channels.AMFChannel”>
       <endpoint url=”http://{server.name}:{server.port}/{context.root}/messagebroker/amfpolling” class=”flex.messaging.endpoints.AMFEndpoint”/>
    </channel-definition>
    </channels>
</services-config>

Listing 1: services-config.xml - Updated to contain only the channels defined.

Now select the Servers tab in Eclipse. If the tab is not visible you can make it visible by choosing Windows > Show View > Servers. Right-click the Tomcat Server and select Add and Remove. To add the flexspring web application to the server, select it in the Available list and then click Add. Finally, click Finish.

Next, you need to add the required dependencies to the flexspring web application. Copy all of the Spring Framework libraries / JAR files (located in the dist folder) to the WebContent/WEB-INF/lib folder. Also copy the Spring BlazeDS Integration library (located in the dist folder) to the lib folder. Do the same for aopalliance.jar, backport-util-concurrent.jar, cglib-2.2.jar, asm-3.2.jar.

Simple Flex Remoting

To configure the server for simple Flex Remoting first edit the web.xml file in the WebContent/WEB-INF folder. Replace its contents with:


<?xml version=”1.0” encoding=”UTF-8”?>
<web-app xmlns=”http://java.sun.com/xml/ns/javaee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”
  xsi:schemaLocation=”
		http://java.sun.com/xml/ns/javaee
		http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”
  version=”2.5”>
  <listener>
    <listener-class>
       org.springframework.web.context.ContextLoaderListener
  </listener-class>
  </listener>
<listener>
<listener-class>flex.messaging.HttpFlexSession</listener-class>
  </listener>
  <servlet>
     <servlet-name>flexspring</servlet-name>
     <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
  </servlet-class>
     <init-param>
     <param-name>contextConfigLocation</param-name>
 <param-value></param-value>
 </init-param>
     <load-on-startup>1</load-on-startup>
    </servlet>
<servlet-mapping>
     <servlet-name>flexspring</servlet-name>
     <url-pattern>/messagebroker/*</url-pattern>
   </servlet-mapping>
</web-app>

Listing 2: web.xml - Setup for simple Flex Remoting with Spring.

Eclipse may try to change the web-app version to 2.4 instead of 2.5. If this happens just manually change it back to 2.5.

Spring will now handle requests to the /messagebroker/ url.

Now configure Spring by creating an applicationContext.xml file in the WebContent/WEB-INF folder with the following contents:


<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
    xmlns:flex=”http://www.springframework.org/schema/flex”
    xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”


xmlns:context=”http://www.springframework.org/schema/context”
	xsi:schemaLocation=”
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/flex
		http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.0.xsd”>
	<flex:message-broker>
		<flex:remoting-service default-channels=”my-amf”/>
	</flex:message-broker>
	<context:component-scan base-package=”flex” />
</beans>

Listing 3: The basic Spring configuration for Flex Remoting.

Listing 3 sets up the Flex message-broker, which will enable the Flex remoting-service using the my-amf channel. The component-scan will find classes in the “flex” package that have been annotated for Remoting. Typically with Spring, the configuration files are split out into more logical pieces. The approach used in Listing 3 is a simple way to get started but does not represent the best practice for Spring config file organization. For more details on how to better organize Spring config files see: http://refcardz.dzone.com/refcardz/spring-configuration

Now create a simple Java class that will be exposed through the AMF channel to a Flex application. In the src folder create a new Java Class in the flex package with the name “HelloWorldService”. Set the contents of the HelloWorldService.java file to:


package flex;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.flex.remoting.RemotingInclude;
import org.springframework.stereotype.Service;
@Service
@RemotingDestination
public class HelloWorldService {
	@RemotingInclude
	public String sayHello(String name) {
		return “howdy, “ + name;
	}
}

Listing 4: HelloWorldService.java - A simple Java object exposed for remoting through Spring annotations.

On the HelloWorldService class you will notice two annotations. The @Service annotation tells Spring that the class is a Service and the @RemotingDestination annotation exposes the class as a remoting endpoint for Flex. This class also contains a single method named sayHello, which simply takes a string and returns a slightly modified version of the string. By default all public methods on a class are available for remoting. You can keep a public method from being exposed as a remoting endpoint by using the @RemotingExclude annotation.

Create the Flex Application

Now you can create a Flex application that will call the sayHello method on HelloWorldService. Remember that Flex applications run on the client side so all interactions with a server must happen over some remote call. Usually (and in the case here) these calls happen over HTTP. They can use a variety of serialization options including SOAP, JSON, and RESTful XML. In this case, Flex Remoting will use the binary AMF serialization protocol inside of HTTP request / response bodies.

To begin building the Flex application, simply create a new Flex Project in Eclipse. In the New Flex Project wizard, type sayHello as the name, select Web as the Application type, and set the Flex SDK Version to Flex 4.0 (usually the default). Also select J2EE as the Application Server Type, enable Use Remote Object Access Service, and select BlazeDS. Ensure that the Create Combined Java/Flex Project Using WTP option is not checked and then click Next. Now enter the information for your flexspring project. The Root folder is the WebContent folder in your flexspring project. The Root URL should be http://localhost:8080/flexspring/. The Context root should be /flexspring.

Click Finish to create the project. You should now see the template code for the application. Replace the code with the following:


<?xml version=”1.0” encoding=”utf-8”?>
<s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009”
		xmlns:s=”library://ns.adobe.com/flex/spark”
		xmlns:mx=”library://ns.adobe.com/flex/mx”>
<fx:Declarations>

        <s:RemoteObject id=”ro” destination=”helloWorldService”
endpoint=”http://localhost:8080/flexspring/messagebroker/amf”/>
	</fx:Declarations>
	<s:layout><s:VerticalLayout/></s:layout>
	<s:TextInput id=”t”/>
	<s:Button label=”sayHello” click=”ro.sayHello(t.text)”/>
	<s:Label text=”{ro.sayHello.lastResult}”/>
</s:Application>

Listing 5: sayHello.mxml - Basic Flex application using Remoting with Spring.

Hot Tip

Externalizing Configuration These examples hardcode URLs into the applications. This is not recommended for real-world applications. Configuration should be externalized with Flex using one of the many methods available. Flex frameworks like Swiz, Parsley, or Spring ActionScript provide straightforward ways to externalize configuration. Using these methods is highly recommended for real-world applications.

When you save the file it should automatically compile. When it is compiled it should automatically be deployed in your web application. You are now ready to start the server and test the application. Go to the Servers View in Eclipse and start the Tomcat server. Watch the console and make sure that there are no startup errors.

Now run the sayHello application (one way is to right-click the sayHello. mxml file, select Run As, and then select W eb Application). Your browser should open the sayHello.html file that then downloads and runs the Flex application. Type your name in the TextInput box and click the sayHello button. This will initiate a Flex Remoting request to the Tomcat server calling the Spring DispatcherServlet, which then will look up the service based on the destination helloWorldService. This destination is automatically mapped to the HelloWorldService Spring Bean. Then the sayHello method will be invoked on the bean, passing in the String that was specified in the RemoteObject call on the client. The method returns a new String, which is then serialized into AMF, inserted into the HTTP Response body, and sent back to the client. On the client side the Flex application will parse the AMF and then set the ro.sayHello.lastResult property to what was returned from the server. Data binding in the Label will note the property change and refresh its view of the data.

You now have completed a basic web application with a Flex application communicating with Spring through BlazeDS using the Spring BlazeDS Integration! Next you will add Hibernate into t he mix and see how the Flash Builder 4 data-centric development featur es can help you quickly build data-driven Flex applications.

Integrating Flex with Hibernate through Spring

Using the same flexspring server as the Remoting example you can now add Hibernate to do data persistence. To get started you first need some additional Java libraries:

Extract the libraries and copy their JAR files into the WEB-INF/lib folder. For Hibernate copy the hibernate3.jar file, the JAR files in t he lib/required folder, and the JAR file in the lib/jpa folder. For slf4j copy the slf4j-simple-1.5.8.jar file and for H2 copy the h2-1.2.134.j ar file.

Now you will need to update the Spring config file so that your c ode can connect to an H2 database. Update the applicationContext.xml file with the following contents:


<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
	xmlns:flex=”http://www.springframework.org/schema/flex”
	xmlns:context=”http://www.springframework.org/schema/context”
	xmlns:tx=”http://www.springframework.org/schema/tx”
	xmlns:jdbc=”http://www.springframework.org/schema/jdbc”
	xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
	xsi:schemaLocation=”
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/flex
		http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		
		http://www.springframework.org/schema/jdbc
		http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd”>
	<flex:message-broker>
		<flex:remoting-service default-channels=”my-amf” />
	</flex:message-broker>
	<context:component-scan base-package=”flex” />
	<tx:annotation-driven />
	<jdbc:embedded-database id=”dataSource” type=”H2”/>
	<bean id=”sessionFactory”
class=”org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean”>
		 <property name=”dataSource” ref=”dataSource” />
		 <property name=”packagesToScan” value=”flex” />
		 <property name=”hibernateProperties”>
<props>
		   <prop key=”hibernate.dialect”>org.hibernate.dialect.H2Dialect</prop>
		   <prop key=”hibernate.hbm2ddl.auto”>create</prop>
		   </props>
		</property>
	</bean>
	<bean id=”transactionManager”
		class=”org.springframework.orm.hibernate3.HibernateTransactionManager”>
		<property name=”sessionFactory” ref=”sessionFactory” />
	</bean>
</beans>




Listing 6: applicationContext.xml - Hibernate and H2 Spring configuration.

The changes to the Spring config file introduce the ability to apply transactions through annotations (which you will see shortly), a DataSource to create a database connection, a SessionFactory used to manage the Hibernate Session, and a TransactionManager that handles the database transactions through the SessionFactory. The SessionFactory scans for Hibernate entities in the flex package.

In order to use the new data-centric development features in Flash Builder 4 you need to add the following servlet and servlet map ping to the web.xml file:


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

Listing 7: web.xml snippet - Enable the data-centric development in Flash Builder 4.

This new servlet from BlazeDS enables Flash Builder 4 to intr ospect the services that are configured on a server. If you add this servlet in a real application make sure that you either configure the security for the RDSDispatchServlet or remove the servlet when the application goes to production. Leaving a wide open RDSDispatchServlet in a production system can have adverse security implications.

Now create a Hibernate bean by cr eating a new Java class in the flex package called Friend with the following contents:


package flex;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Friend {
	@Id
	@GeneratedValue
	public String getId() {
	return id;
	}
	public void setId(String id) {
	this.id = id;
	}
	public String getName() {
	return name;
	}
	public void setName(String name) {
	this.name = name;
	}
	private String id;
	private String name;
}

Listing 8: Friend.java - The Hibernate Entity used to persist data.

You will notice that the Friend class has an @Entity annotation on it. This annotation enables this class to be used by Hibernate for data persistence. The getId() method of Friend has two annotations. The @Id annotation uses the id property as the primary key for the entity while the @GeneratedValue annotation will tell Hibernate to automatically assign a value when a new Entity is created. In order to communicate with the Friend entity from Flex you will need a Remoting service to connect to. Similar to the HelloWorldService example, you can create a Spring bean that will be exposed to Flex. Create a new Java class in the flex package called FriendService with the following contents:


package flex;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.flex.remoting.RemotingInclude;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@RemotingDestination
public class FriendService {
	private SessionFactory sessionFactory;
	@Autowired
	public void setSessionFactory(SessionFactory factory) {
		sessionFactory = factory;
	}
	@SuppressWarnings(“unchecked”)
	@RemotingInclude
	@Transactional
	public List<Friend> getFriends() {
	return sessionFactory.getCurrentSession().createQuery(“from Friend”).list();
	}
	@RemotingInclude
	@Transactional
	public void createFriend(String name) {
		Friend f = new Friend();
		f.setName(name);
		sessionFactory.getCurrentSession().save(f);
	}
}

Listing 9: FriendService.java - A Spring bean to manage Friend entities.

The FriendService class is annotated with @Repository to allow it to connect to a DataSource and @RemotingDestination to expose it as a Flex Remoting destination. The SessionFactory is Autowired into instances of the FriendService using Spring’s dependency injection. In this case the SessionFactory that is injected is defined in the applicationContext.xml file. The getFriends method is included for Remoting access but also uses the @Transactional annotation to wrap the database query into a transaction. The createFriend method, which simply creates a new Friend entity and saves, is also Transactional and included for Remoting.

After making these changes, restart your Tomcat server. Verify that there were no errors on startup.

Create the Flex Application

Create a new Flex project called myFriends. Specify the same parameters as in the first example for the Application Type, Flex SDK version, and Server technology. Click Next and specify the same parameters as the sayHello project for Server Location. Click Finish.

Instead of writing code this time, switch to Design view for the myFriends.mxml file. Now in the Data/Services V iew click Connect to Data/Service, select BlazeDS, and then click Next. When you ar e asked for a username and password, check No Password Required and click OK. You should now see a list of services that ar e configured on your server. Among them should be friendService; select the checkbox next to that service and then click Finish. This automatically generates the client-side service stubs and value objects used to connect to friendService. In the Data/Services view you should now see the friendService methods and data types used.

To create the UI for the application, locate the DataGrid component in the Components view. Drag the DataGrid onto the Design canvas of the myFriends.mxml application. Now drag the getFriends met hod from the Data/Services View onto the DataGrid of the myFriends.mxml application. When you are prompted to confirm how you want to bind the service call to the DataGrid, click OK. Y our DataGrid should now have two columns: id and name.

Next, you need some way to cr eate new Friend objects. Right-click the createFriend method in the Data/Services V iew and select Generate Form. When you are presented with a dialog box asking for details about how to create the form, simply click Finish. You should now have a form in the Design canvas for myFriends.mxml. Y ou can reposition the form so that it doesn’t overlap the DataGrid. Now double-click the arg0 label and rename it by typing Name.

While you were manipulating elements in the Design canvas for the myFriends.mxml application you were actually writing Flex code. Switch back to Source view so you can see the code and make a few minor changes to the generated code.

First, you need to tell the generated FriendService instance how to connect to the server. Find the <services:FriendService tag and add a property called endpoint with a value of http://localhost:8080/flexspring/messagebroker/amf, for example:


<services:FriendService id=”friendService”
endpoint=”http://localhost:8080/flexspring/messagebroker/amf”/>

Listing 10: myFriends.mxml snippet - FriendService with an endpoint.

Another small change you will want to make is to refresh the data in the DataGrid after a new Friend has successfully been cr eated. To do that, first make the event parameter in the dataGrid_ creationCompleteHandler function optional. For example:


protected function dataGrid_creationCompleteHandler(event:FlexEvent=null):void {

Listing 11: myFriends.mxml snippet - Optional FlexEvent parameter.

Finally update the createFriendResult CallResponder so that on a result event the dataGrid_creationCompleteHandler function is called.


<s:CallResponder id=”createFriendResult”
result=”dataGrid_creationCompleteHandler()”/>


Listing 12: myFriends.mxml snippet - Refresh the data on result event

Now run the myFriends application and cr eate a new Friend by typing a name in the TextInput and clicking CreateFriend. Verify that the new Friend shows up in the DataGrid . You now have a Flex application that calls a Spring service to interact with Hibernate!

Hot Tip

Hibernate Lazy Loading and Flex When BlazeDS serializes data to send to Flex, that data must be serializable. This can cause problems with lazy loading of associations in Hibernate. There are several approaches for dealing with this problem. One is to potentially not serialize the same object graph that is defined in Hibernate Entities but instead utilize Data Transfer Objects for serialization to AMF.

Integrating Pub / Sub Messaging with Flex and Spring

Flex Remoting is always done in a request / response manner. Sometimes applications also need to communicate in a publish / subscribe manner. BlazeDS provides the ability for Flex clients to connect to a message service and listen for messages or send messages. The message service can optionally be connected to other messaging systems like JMS, ActiveMQ, or any messaging system supported in Spring Integration.

Sending messages over HTTP is usually technically simple to enable because it can easily be built on HTTP’s request / response nature. However receiving messages is more difficult since the client must initiate connections. To overcome this hurdle BlazeDS has various channels that are configured to do a pseudo push of messages from the server to the client. The primary channels available in BlazeDS are HTTP Streaming, HTTP Long-Polling, and HTTP Polling. Each of these channels has different advantages and disadvantages. For instance HTTP Streaming provides very low latency for sending messages but consumes one of the available HTTP connections the browser allows to a given site. HTTP Streaming in BlazeDS also uses the default HTTP connector in the Java app server, which usually has a very limited number of concurrent connections available. Java NIO pr ovides a way to work around those connection limits but today NIO-backed connections are only available in Adobe’s commercial superset of BlazeDS, called LiveCycle Data Services. HTTP Long-Polling and HTTP Polling can help alleviate some of the connection load but they also increase latency for sending messages from the server to the client. Ultimately which channel configuration you select will depend on your requirements. It’s important to also note that channels can be configured to do automatic failover. So if an HTTP Streaming connection can’t be made then Flex can try Long-Polling or Polling. Channel configuration is done in the services-config.xml file.

The Spring BlazeDS integration exposes the Messaging features of BlazeDS so that they can be configured in Spring config and easily connected to Spring services and messaging systems. To configure a Messaging destination for Flex simply add the message-service to the message broker in the applicationContext.xml file. Then create a message-destination in that same file. For this example set the id of the message-destination to chat.


<flex:message-broker>
	<flex:remoting-service default-channels=”my-amf” />
	<flex:message-service
		default-channels=”my-streaming-amf,my-polling-amf” />
</flex:message-broker>
<flex:message-destination id=”chat” />

Listing 13: applicationContext.xml - Messaging enabled configuration.

Now create a new Flex Project just as before but call it “chat”. Update the chat.mxml file with the following code:


<?xml version=”1.0” encoding=”utf-8”?>
<s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009”
			xmlns:s=”library://ns.adobe.com/flex/spark”
			xmlns:mx=”library://ns.adobe.com/flex/mx”>
	<fx:Script>
	  import mx.messaging.messages.AsyncMessage;
	</fx:Script>
	<fx:Declarations>
	  <s:ChannelSet id=”channelSet”>
	<s:StreamingAMFChannel
	uri=”http://localhost:8080/flexspring/messagebroker/streamingamf”/>
	<s:AMFChannel
			uri=”http://localhost:8080/flexspring/messagebroker/amfpolling”
			pollingEnabled=”true” pollingInterval=”5”/>
	  </s:ChannelSet>
	<s:Consumer id=”c” destination=”chat” channelSet=”{channelSet}”
				message=”ta.text += event.message.body + ‘\n’”/>
	  <s:Producer id=”p” destination=”chat” channelSet=”{channelSet}”/>
	</fx:Declarations>
	<s:applicationComplete> c.subscribe();</s:applicationComplete>
	<s:layout><s:VerticalLayout/></s:layout>
	<s:TextArea id=”ta” width=”300” height=”150”/>
	<s:TextInput id=”ti”/>
	<s:Button label=”send” click=”p.send(new AsyncMessage(ti.text))”/>
</s:Application>

Listing 14: chat.mxml - A simple Chat application using Flex Messaging

Restart the Tomcat server and run the application. Open two br owser windows to verify that the messaging is happening correctly.

In the Chat application there is a ChannelSet declaration that defines how messages will be sent and received from the server. The first child inside the ChannelSet is the StreamingAMFChannel. Flex will try to make that connection first. Next is the AMFChannel with polling enabled on a 5 second poll interval. Also declar ed in the Chat application is a Consumer, which can listen for messages from the server using the ChannelSet. A message event handler on the Consumer tells the application to append the body of the message to the TextArea. A Producer declaration is used to send messages to the message service. Notice that both the Consumer and Pr oducer have their destination set to chat, which is the id of the message-destination that was defined in the Spring configuration.

An applicationComplete event handler calls the subscribe method on the Consumer to begin listening for messages from the server.

The UI for the Chat application is very simple. The TextArea displays the chat messages. A TextInput allows the user to enter the text for a new chat message, and a Button allows the user to send the message. In the click handler for the Button a new AsyncMessage is created with its body set to the text the user entered in the TextInput. That message is then sent to the Producer, which connects to the server and sends the message. BlazeDS then tries to send that message out to all clients that are connected to the destination. When a connection is available the Consumer will receive any queued messages on the server and fire message events for each message.

Flex Messaging uses AMF internally so complex objects can be sent and received through the message service, just like with Remoting.

On top of the Producer and Consumer APIs, very powerful r eal-time and near real-time applications can be built. These can range from collaborative applications to trader desktops. Sometimes the message service is used simply for application management to do things like notify the client that their version of the data is stale.

Flex and Spring Security

Most real-world Flex applications require a user to login before they can perform certain actions in the application. Enabling user authentication and application security with Flex and Spring is simple to set up and implement. To get started you will need to download Spring Security 3.0.2 from http://www.springsource.org/download and copy the following JAR files into the WEB-INF/lib for the flexspring web app project:

  • spring-security-acl-3.0.2.RELEASE.jar
  • spring-security-config-3.0.2.RELEASE.jar
  • spring-security-cor e-3.0.2.RELEASE.jar
  • spring-security-web-3.0.2.RELEASE.jar

Now modify the applicationContext.xml file to add in some Spring Security information:


<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
	xmlns:flex=”http://www.springframework.org/schema/flex”
	xmlns:context=”http://www.springframework.org/schema/context”
	xmlns:tx=”http://www.springframework.org/schema/tx”
	xmlns:jdbc=”http://www.springframework.org/schema/jdbc”
	xmlns:security=”http://www.springframework.org/schema/security”
	xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
	xsi:schemaLocation=”
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/flex
		http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/jdbc
		http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
		http://www.springframework.org/schema/security
		http://www.springframework.org/schema/security/spring-security-3.0.xsd”>
	<security:global-method-security secured-annotations=”enabled”
		jsr250-annotations=”enabled”/>
	<security:http entry-point-ref=”preAuthenticatedEntryPoint”>
		<security:anonymous enabled=”false”/>
	</security:http>
	<bean id=”preAuthenticatedEntryPoint”
class=”org.springframework.security.web.authentication.Http403ForbiddenEntryPoint”
/>
	<security:authentication-manager>
		<security:authentication-provider>
		  <security:user-service>
		   <security:user name=”john” password=”john” authorities=”ROLE_USER” />
            </security:user-service>
           </security:authentication-provider>
  	</security:authentication-manager>
	<flex:message-broker>
		<flex:remoting-service default-channels=”my-amf” />
		<flex:message-service
		  default-channels=”my-streaming-amf,my-polling-amf” />
		<flex:secured/>
	</flex:message-broker>
... (file truncated)

Listing 15: applicationContext.xml snippet - Enable Security annotations.

The configuration in Listing 15 simply tells Spring about a basi c user-service authentication-provider. Real-world applications use a database or LDAP server for user credentials and authentication.

Add the following filter, and filter-mapping to the web.xml file to enable Spring Security for the web application:


<filter>
<filter-name>springSecurityFilterChain</filter-name>
	<filter-class>
	org.springframework.web.filter.DelegatingFilterProxy
	</filter-class>
	</filter>
<filter-mapping>
	<filter-name>springSecurityFilterChain</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

Listing 16: web.xml snippet - Enables Spring Security for the web application.

Modify the HelloWorldService.java file to protect calls to the sayHello method by adding the following annotation above the method:


@Secured(“ROLE_USER”)

Listing 17: HellowWorldService.java snippet - Only users with ROLE_USER can call the sayHello method

Make sure you add the import statement for org.springframework. security.access.annotation.Secured then save the class and restart Tomcat. Now run the sayHello Flex application. Remote calls to the helloWorldService sayHello method should now fail. Update the sayHello.mxml file with the following contents:



<?xml version=”1.0” encoding=”utf-8”?>
<s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009”
			xmlns:s=”library://ns.adobe.com/flex/spark”
			xmlns:mx=”library://ns.adobe.com/flex/mx”>
		<fx:Script>
		import mx.rpc.AsyncResponder;
		import mx.rpc.events.FaultEvent;
		import mx.rpc.events.ResultEvent;
		private function handleFault(event:FaultEvent, o:Object=null):void {
		  l.text = event.fault.faultString;
		}
    </fx:Script>
    <fx:Declarations>
		<fx:Boolean id=”loggedIn”>false</fx:Boolean>
		<s:RemoteObject id=”ro”
			destination=”helloWorldService”
			fault=”handleFault(event)”>
		<s:channelSet>
			<s:ChannelSet>
				<s:AMFChannel uri=”/flexspring/messagebroker/amf”/>
			</s:ChannelSet>
		</s:channelSet>
	  </s:RemoteObject>
	</fx:Declarations>
	<s:layout><s:VerticalLayout/></s:layout>
	<s:TextInput id=”t”/>
	<s:Button label=”sayHello” click=”ro.sayHello(t.text)”/>
	<s:Label id=”l” text=”{ro.sayHello.lastResult}”/>
	<s:Button label=”login” enabled=”{!loggedIn}”>
     <s:click>
	   ro.channelSet.login(‘john’, ‘john’).addResponder(new AsyncResponder(
	     function(result:ResultEvent, o:Object):void {
			loggedIn = true;
			l.text = “logged in”;
	     }, handleFault));
       </s:click>
    </s:Button>
    <s:Button label=”logout” enabled=”{loggedIn}”>
       <s:click>
         ro.channelSet.logout().addResponder(new AsyncResponder(
            function(result:ResultEvent, o:Object):void {
               loggedIn = false;
               l.text = “logged out”;
         }, handleFault));
       </s:click>
     </s:Button>
</s:Application>

Listing 18: sayHello.mxml - Enables the user to login and logout.

The updated sayHello application now has buttons that allow the user to login to the server. In this example the credentials for login are hardcoded. For a real-world application the credentials would likely come from TextInput controls – allowing the user to enter their username and password. Also the Boolean variable loggedIn tracks whether the user is authenticated or not. This Boolean is also used to enable and disable the login and logout buttons.

Rerun the sayHello application and try to call the sayHello method when not logged in. Now login and try it again. That is how simple it is to set up Spring Security with Flex!

CONCLUSION

In this Refcard, you learned how to use Flex Remoting and Messaging to connect to Spring and Hibernate. You also learned how to use Spring Security with Flex. As you can see, the Spring BlazeDS Integration project makes integrating Flex and Spring easy and straightforward. The combination of the two technologies creates a powerful platform for building robust RIAs. You can learn more about integrating Flex and Spring on the Spring BlazeDS Integration project site: http://www.springsource.org/spring-flex

To receive help with Spring BlazeDS integration ask questions in the Spring Forums: http://forum.springsource.org/forumdisplay.php?f=61

Download the full source code, configuration, and dependencies for all of the projects from: http://static.springsource.org/spring-flex/refcard/flexspring-refcard_completed.zip

Find screencasts which explain these code examples at: http://www.jamesward.com/flex-and-java-resources/

About The Authors

Photo of author Jon Rose

Jon Rose

Jon Rose is the Flex Practice Director for Gorilla Logic, an enterprise software consulting company located in Boulder, Colorado. He is an editor and contributor to InfoQ.com, an enterprise software community. Visit his website at: www.ectropic.com Gorilla Logic, Inc. provides enterprise Flex and Java consulting services tailored to businesses in all industries. www.gorillalogic.com

Photo of author James Ward

James Ward

James Ward is a Technical Evangelist for Flex at Adobe. He travels the globe speaking at conferences and teaching developers how to build better software with Flex. Visit his website at: www.jamesward.com First Steps in Flex is an introductory Flex book by James Ward and Bruce Eckel. It will give you just enough information, and just the right information, to get you started learning Flex. For more information visit: http://www.firststepsinflex.com

Recommended Book

Flex

First Steps in Flex will give you just enough information, and just the right information, to get you started learning Flex. Enough so that you feel confident in taking your own steps once you finish the book. For more information visit http://www.firststepsinflex.com.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

JDBC Best Practices

By Jesse Davis

24,814 Downloads · Refcard 101 of 151 (see them all)

Download
FREE PDF


The Essential JDBC Cheat Sheet

JDBC Best Practices has something for every developer. JDBC was created to be the standard for data access on the Java Platform. JDBC has evolved since that time from a thin API on top of an ODBC driver to a fully featured data access standard whose capabilities have now surpassed ODBC. This DZone Refcard starts off with JDBC basics including descriptions for each of the 5 Driver Types. This is followed up with some advanced JDBC on Codeless Configuration, Single Sign-on with Kerberos, Debugging and Logging.
HTML Preview
JDBC Best Practices

JDBC Best Practices

By Jesse Davis

A BRIEF HISTORY

Sun Microsystems created JDBC in the 90s to be the standard for data access on the Java Platform. JDBC has evolved since that time from a thin API on top of an ODBC driver to a fully featured data access standard whose capabilities have now surpassed its aging brother, ODBC. In recent applications, JDBC connects persistence layers (such as Hibernate or JPA) to relational data sources; but the JDBC API with its accompanying drivers are always the final piece connecting Java apps to their data! For more in depth (and entertaining) history, watch this movie on the history of Java and JDBC:

http://www.youtube.com/watch?v=WAy9mgEYb6o

JDBC BASICS

Connecting to a Server

Getting a basic Connection object from the database is the first operation to get a handle on. The code snippet below gets a connection to a SQL Server database. Note that the Class.forName line is unnecessary if you are using a JDBC 4.0 driver with Java SE 6 or above.


String url = “jdbc:datadirect:sqlserver://nc-cqserver:1433;databaseName=testDB;user=test;password=test”;
try {
  Class.forName(“com.ddtek.jdbc.sqlserver.SQLServerDriver”);
  Connection con = DriverManager.getConnection(url);
}
catch (Exception except) {
    SQLException ex = new SQLException(
		“Error Establishing Connection: “ +
		except.getMessage());
		throw ex;
}

It is good to get metaData from the Connection object to see what driver and server version you are using. This comes in handy when its time to debug. Printing to system out or logging to a file is preferable:


DatabaseMetaData dbmd = con.getMetaData();
System.out.println( “\nConnected with “ +
	dbmd.getDriverName() + “ “ + dbmd.getDriverVersion()
	+ “{ “ + dbmd.getDriverMajorVersion() + “,” +
	dbmd.getDriverMinorVersion() +” }” + “ to “ +
	dbmd.getDatabaseProductName() + “ “ +
	dbmd.getDatabaseProductVersion() + “\n”);

Retrieving Data

A straightforward approach to retrieving data from a database is to simply select the data using a Statement object and iterate through the ResultSet object:


Statement stmt = con.createStatement();
ResultSet results = stmt.executeQuery(“Select * from foo”);
String product;
int days = 0;
while (results.next()){
	product = results.getString(1);
	 days = results.getInt(2);
	 System.out.println(product + “\t” + days);
}

Hot Tip

The JDBC specification allows for fetching all data types using getString or getObject; however, it is a best practice to use the correct getXXX method as demonstrated in the code sample above to avoid unnecessary data conversions.

Executing a PreparedStatement

Use a PreparedStatement any time you have optional parameters to specify to the SQL Statement, or values that do not convert easily to strings, for example BLOBs. It also helps prevent SQL injection attacks when working with string values.


PreparedStatement pstmt = con.prepareStatement(“INSERT into table2 (ID, lastName, firstName) VALUES (?,?,?)”);
pstmt.setInt(1, 87);
pstmt.setString(2, “Picard”);
pstmt.setString(3, “Jean-Luc”);
rowsInserted += pstmt.executeUpdate();

Calling a Stored Procedure via CallableStatement

Use a CallableStatement any time you wish to execute a stored procedure on the server:


CallableStatement cstmt = con.prepareCall(“{CALL STPROC1 (?)}”);
cstmt.setString(1, “foo”);
ResultSet rs = cstmt.executeQuery();
rs.next();
int value = rs.getInt(1);

Hot Tip

CallableStatements can return resultSets, even when inserting data on the server. If the application doesn’t know if results should be returned, check for results by issuing a call to getMoreResults() after execution.

DRIVER TYPES AND ARCHITECTURE

TYPE 1: The JDBC-ODBC Bridge

The JDBC-ODBC Bridge was the architecture that the first JDBC drivers adopted. This architecture requires an implementation of the JDBC API that then translates the incoming JDBC calls to the appropriate ODBC calls using the JNI (Java Native Interface). The requests are then sent to the underlying ODBC driver (which at the time was just a shell over the database native client libraries). The bridge implementation shipped with the JDK so you only needed the ODBC drivers and native DB client libraries to get started. Although this was a klunky and headache prone approach, it worked.

JDBC-ODBC

TYPE 2: Client Based

The next generation of JDBC Drivers was the ever popular Type 2 driver architecture. This architecture eliminated the need for the ODBC driver and instead directly called the native client libraries shipped by the database vendors. This was quickly adopted by the DB vendors as it was quick and inexpensive to implement since they could reuse the existing C/C++ based native libraries. This choice still left Java developers worrying about version and platform compatibility issues (i.e. client version 6 is not supported on HP-Itanium processors).

ODBC

Hot Tip

Some vendors still do their new development in their native clients first. So, don’t assume that if their website states that the JDBC driver supports Kerberos that they mean their Type 4 driver – they may mean Type 2!

TYPE 3: Two Tier Architecture

Type 3 drivers sought to be a 100% Java solution but never really gained much traction. Type 3 drivers had a Java client component and a Java server component, where the latter actually talked to the database. Although this was technically a full Java solution, the database vendors did not like this approach as it was costly – they would have to rewrite their native client libraries which were all C/C++. In addition, this didn’t increase the architectural efficiency as we are really still a 3 tier architecture so it is easy to see why this was never a popular choice.

Two

TYPE 4: Wire Protocol Drivers

The most popular JDBC driver architecture to date is Type 4. This architecture encapsulates the entirety of the JDBC API implementation along with all the logic for communicating directly with the database in a single driver. This allows for easy deployment and streamlines the development process by having a single tier and a small driver all in a 100% java package.

driver

Hot Tip

Type 4 drivers have been the traditional favorite of Java application developers since its inception due to the clean design and ease of use; drop in the driver jar and you’re up and running!

TYPE 5: NEW!

While not yet officially sanctioned by the JDBC Expert Group, there is quite a bit of discussion surrounding the new Type 5 driver proposal in the JDBC community. Getting down to the real functional differences, we see this list as the requirements for Type 5 Drivers as follows:

Codeless Configuration The ability to modify options, check statistics and interact with the driver while it is running. Typically through a standard JMX MBean.
Performance Architecture Drivers specifically designed for multi-core, 64 bit, and virtualized environments.
Clean Spec Implementation Strict adherence to the JDBC standard, solving problems within the specification instead of using proprietary methods that promote vendor lock-in.
Advanced Functionality Type 5 drivers unlock code that has been trapped in the vendor native client libraries and bring that into the Java community. Features include but are not limited to: Bulk Load, Client side High Availability, Kerberos, and others.

PERFORMANCE CONSIDERATIONS

Pooling (Object Re-use)

Hot Tip

Pooling objects results in significant performance savings. In JDBC, pooling Connection and Statement objects is the difference between a streamlined app and one that will consume all your memory. Make use of these pooling suggestions for all your JDBC applications!

Connection Pooling – Enabling Connection pooling allows the pool manager to keep connections in a ‘pool’ after they are closed. The next time a connection is needed, if the connection options requested match one in the pool then that connection is returned instead of incurring the overhead of establishing another actual socket connection to the server

Statement Pooling – Setting the MaxPooledStatements connection option enables statement pooling. Enabling statement pooling allows the driver to re-use PreparedStatement objects. When PreparedStatements are closed they are returned to the pool instead of being freed and the next PreparedStatement with the same SQL statement is retrieved from the pool rather than being instantiated and prepared against the server.

Hot Tip

Don’t use PreparedStatements by default! If your SQL statement doesn’t contain parameters use the Statement object instead – this avoids a call to internal and wire level prepare() methods and increases performance!

MetaData Performance

  • Specify as many ar guments to DatabaseMetaData methods as possible. This avoids unnecessary scans on the database. For example, don’t call getTables like this:

ResultSet rs = dbmd.getTables(null,null,null,null);

Specifying at least the schema will avoid returning information on all tables for every schema when the request is sent to the server:


ResultSet rs = dbmd.getTables(null,”test”,null,null);

  • Most JDBC drivers populate the ResultSetMetaData object at fetch time because the needed data is returned in the server responses to the fetch request. Some underutilized pieces of ResultSetMetaData include:

ResultSetMetaData.getColumnCount()
ResultSetMetaData.getColumnName()
ResultSetMetaData.getColumnType()
ResultSetMetaData.getColumnTypeName()
ResultSetMetaData.getColumnDisplaySize()
ResultSetMetaData.getPrecision()
ResultSetMetaData.getScale()

Hot Tip

Instead of using getColumns to get data about a table, consider issuing a dummy query and using the returned ResultSetMetaData which avoids querying the system tables!

Commit Mode

When writing a JDBC application, make sure you consider how often you are committing transactions. Every commit causes the driver to send packet requests over the socket. Additionally, the database performs the actual commit which usually entails disk I/O on the server. Consider removing autocommit mode for your application and using manual commit instead to better control commit logic:


Connection.setAutoCommit(false);

Hot Tip

Virtualization and Scalability are key factors to consider when choosing a JDBC driver. During the Performance Testing phase of your development cycle, ensure that your JDBC driver is using the least amount of CPU and Memory possible. You can get memory and CPU performance numbers from your driver vendor to see how the drivers will scale when deployed in a Cloud or other virtualized environment.

Network Traffic Reduction

Reduce network traffic by following these guidelines.

Technique Benefit
Use addBatch() instead of using PreparedStatements to insert. Sends multiple insert requests in a single network packet
Eliminate unused column data from your SQL statements Removing long data and LOBs from your queries can save megabytes of wire transfer!
Ensure that your database is set to the maximum packet size and that the driver matches that packet size For fetching larger result sets, this reduces the number of total packets sent/received between the driver and server

JDBC DATA TYPES

Below is a list of common JDBC types and their default mapping to Java types. For a complete list of data types, conversion rules, and mapping tables, see the JDBC conversion tables in the JDBC Specification or the Java SE API documentation.

JDBC Types Java Type
CHAR, VARCHAR,LONGVARCHAR java.lang.String
CLOB java.sql.Clob
NUMERIC, DECIMAL java.math.BigDecimal
BIT, BOOLEAN Boolean
BINARY, VARBINARY,LONGVARBINARY byte[]
BLOB java.sql.Blob
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT, DOUBLE double

WHAT’S IN A DRIVER?

To illustrate what a JDBC driver does under the covers, take a look at this ‘anatomy of a JDBC driver’ diagram.

Diagram1"

ADVANCED JDBC

Hot Tip

These advanced features are complex and meant as an overview. For all the bells and whistles for these advanced options, check your JDBC driver documentation!

Debugging and Logging

Well-written JDBC drivers offer ways to log the JDBC calls going through the driver for debugging purposes. As an example, to enable logging with some JDBC drivers, you simply set a connection option to turn on this spying capability:


Class.forName(“com.ddtek.jdbc.sqlserver.SQLServerDriver”);

Connection conn = DriverManager.getConnection
(“jdbc:datadirect:sqlserver://Server1:1433;User=TEST;Password=secret;
SpyAttributes=(log=(file)C:\\temp\\spy.log;linelimit=80;logTName=yes;t
imestamp=yes)”);

Codeless Configuration (Hibernate and JPA)

Codeless Configuration is the ability to change driver behavior without having to change application code. Using a driver under something like Hibernate or JPA means that the user cannot use proprietary extensions to the JDBC objects and should instead control and change driver behavior through connection options.

Additionally, codeless configuration is the ability to monitor and change JDBC driver behavior while the driver is in use. For example, using a tool like JConsole to connect to a driver exported MBean and check the PreparedStatement pool stats as well as importing/exporting new statements on the fly to fine tune application performance.

Encrypt Your Data using SSL

Ensure that your data is secure by encrypting the wire traffic between the server and client using SSL encryption:

  1. Set the EncryptionMethod connect option to SSL.
  2. Specify the location and password of the trustStore file used for SSL server authentication. Set connect options or system properties (javax.net.ssl.trustStore and javax.net.ssl.trustStorePassword).
  3. If your database server is configured for SSL client authentication, configure your keyStore information:
    • Specify the location and password of the keyStore file. Either set connect options or Java system properties (javax.net.ssl.keyStore and javax.net.ssl.keyStorePassword).
    • If any key entry in the keyStore file is passwordprotected,set the KeyPassword property to thekey password.

Single Sign-on with Kerberos

Kerberos is an authentication protocol, which enables secure proof of identity over a non-secure network. It is also used for enabling single sign-on across multiple sites by delegating credentials. To enable Kerberos:

  1. Set the authenticationMethod connect option to Kerberos.
  2. Modify the krb5.conf file to contain your Kerberos realm and the KDC name for that realm. Alternatively, you can set the java.security.krb5.realm and java.security.krb5.kdc system properties.
  3. If using Kerberos authentication with a Security Manager,grant security permissions to the application and driver.

Hot Tip

These security features are not supported by all databases and database versions. Check to ensure your database is setup appropriately before attempting Kerberos and SSL connections.

Application Failover

Application failover is the ability for a driver to detect a connection failure and seamlessly reconnect you to an alternate server. Various types of failover exist for JDBC drivers so check your driver documentation for support - the most common are listed below:

Connection Failover In the case of the primary connection being unavailable, the connection will be established with the alternate server.
Extended Failover While the application is running, if a connection failover occurs, the driver will reconnect to an alternate server and post a transaction failure to the application.
Select Failover Same as extended, except instead of posting a transaction failure, this level will reposition any ResultSets, so the application will not know there was a failure at all.

Bulk Loading

Loading large amounts of data into a database quickly requires something more powerful than standard addBatch(). Database vendors offer a way to bulk load data, bypassing the normal wire protocol and normal insert procedure. There are 2 ways to use Bulk Loading with a JDBC driver that supports it:

  1. Set enableBulkLoad connect option to true. This will make addBatch() calls use the bulk load protocol over the wire.
  2. Use a Bulk Load object:

// Get Database Connection

Connection con = DriverManager.getConnection(“jdbc:datadirect:orac
le://server3:1521;ServiceName=ORCL;User=test;Password=secret”);

// Get a DDBulkLoad object

DDBulkLoad bulkLoad = DDBulkLoadFactory.getInstance(con);
bulkLoad.setTableName(“GBMAXTABLE”);
bulkLoad.load(“tmp.csv”);

// Alternatively, you can load from any ResultSet object into the
target table:

bulkLoad.load(results);

Hot Tip

For additional Bulk Load options, check the JDBC driver documentation.

SQL QUICK REFERENCE

Basic Syntax Examples

SQL Construct Example
SELECT statement SELECT * from table1
SELECT (col1,col2,…) from table1
WHERE clause SELECT (col1, col2, col3)
FROM table1 WHERE col1 = ‘foo’
ORDER BY clause SELECT (col1,col2,…)
FROM table_name
ORDER BY column_name [ASC|DESC]
GROUP BY clause SELECT column_name, aggregate_
function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
INSERT statement
(all columns implicit)
INSERT INTO table1
VALUES (val1, val2, value3,…)
(explicit columns) INSERT INTO table2
(col1,col2,…)
VALUES (val1, val2, value3,…)
UPDATE statement UPDATE table1
SET col1=val1, col2=val2,…
WHERE col3=some_val
DELETE statement DELETE FROM table1
WHERE col2=some_val

Escape Clauses

Escape Type Example
Call (a.k.a. stored procedure {call statement}
{call getBookValues (?,?)}
Function {fn functionCall}
SELECT {fn UCASE(Name)} FROM Employee
Outer Join {oj outer-join}
where outer-join is
table-reference {LEFT | RIGHT | FULL}
OUTER JOIN
{table-reference | outer-join} ON
search-condition
SELECT Customers.CustID, Customers.
Name, Orders.OrderID, Orders.Status
FROM {oj Customers LEFT OUTER JOIN
Orders ON Customers.CustID=Orders.
CustID} WHERE Orders.Status=’OPEN’
Date Escape {d yyy-mm-dd}
UPDATE Orders SET OpenDate={d ‘2005-
01-31’} WHERE OrderID=1025
Time Escape {t hh:mm:ss}
UPDATE Orders SET OrderTime={t
‘12:30:45’} WHERE OrderID=1025
TimeStamp Escape {ts yyyy-mm-dd hh:mm:ss[.f...]}
UPDATE Orders SET shipTS={ts ‘2005-02-
05 12:30:45’} WHERE OrderID=1025

Hot Tip

To get a listing of the functions supported by a given JDBC driver, use the getter methods on the DatabaseMetaData object: getStringFunctions(), getNumericFunctions(), getTimeDateFunctions(), etc.
WildCard Description and Example
% (percent) Subsititute for zero or more characters.
SELECT * from emp where name like ‘Da%’
_ (underscore) Substitute for exactly one character.
SELECT * from books where title like ‘_at in the Hat’
[charlist] Any single character in the charlist.
Select * from animals where name like ‘[cb]at’
[!charlist]
-or-
[^charlist]
Any single character not in the charlist.
Select * from animals where name like ‘[!cb]at’
Select * from animals where name like ‘[^cb]at’

JDBC WITH HIBERNATE

Hibernate is one of the most popular Object Relational Mapping (ORM) frameworks used with JDBC. It is important to note that even if you choose to use Hibernate instead of writing pure JDBC, Hibernate must use a JDBC driver to get to data! Therefore, Hibernate does not replace JDBC as the data connectivity layer, it merely sits on top of it to interface with the application:

Hibernate"

Hot Tip

When choosing a driver to use with Hibernate, ensure your driver supports Codeless Configuration so that you can tune performance and change driver behavior without having to modify the Hibernate code!

When writing Hibernate applications it is important to understand the main files used to setup a Hibernate environment:

Hibernate File Purpose
Dialects (org.hibernate.dialect.*) Describes the SQL behavior of the JDBC driver and database to which the application is connecting.
Configuration File (hibernate.properties or hibernate.cfg.xml) Contains the hibernate configuration settings, such as: JDBC driver and connection information, dialect information, mapping information, etc.
Mapping File The mapping file contains the mapping between the application defined objects and the relational data stored in the database.

Hot Tip

Not all JDBC drivers are created equal! Look for a set of JDBC drivers that can use a single dialect to connect to multiple versions of a database. There’s nothing worse than deploying your application with an Oracle 8 dialect and discover that you need to redeploy with an Oracle 10 dialect!

About The Authors

Photo of author Jesse Davis

Jesse Davis

Jesse Davis watched his Dad code on his Apple IIC Plus, and his addiction to technology began. He used his first PC (a Packard Bell) in high school to run Slackware Linux and began writing shell scripts and simple C applications. Honing his skills as a Computer Engineer at North Carolina State University, Jesse loved the challenge of combining hardware and software and concentrated on microprocessor architecture and design - graduating with honors in Y2K. Today, he enjoys teaching others about the latest technological breakthroughs and enjoys building robots and woodworking projects with his kids. During the day, he is the Senior Engineering Manager for the Progress|DataDirect Connect product line, and has more than 12 years of experience developing database middleware, including JDBC and ODBC drivers, ADO.NET providers, and data services. Jesse is responsible for product development initiatives and forward looking research, and is an active member of the JDBC Expert Group, working on the next version of JDBC.

Blog: http://blogs.datadirect.com/
Twitter: @jldavis007

Recommended Book

The Data Access Handbook

Performance and scalability are more critical than ever in today’s enterprise database applications, and traditional database tuning isn’t nearly enough to solve the performance problems you are likely to see in those applications. Nowadays, 75-95% of the time it takes to process a data request is typically spent in the database middleware. Today’s worst performance and scalability problems are generally caused by issues with networking, database drivers, the broader software/hardware environment, and inefficient coding of data requests. In The Data Access Handbook, two of the world’s leading experts on database access systematically address these issues, showing how to achieve remarkable improvements in performance of real-world database applications.


Share this Refcard with
your friends & followers...

DZone greatly appreciates your support.


Your download should begin immediately.
If it doesn't, click here.

Daily Dose - Hibernate 3.5.2 Final Released

JBoss has released the final version of Hibernate 3.5.2.  The maintenance release fixes problems with querying and incorrect results.  The artifacts have all been published in the new JBoss.org Maven repository, based on Nexus Pro.  Go get it at...

1 replies - 13823 views - 05/15/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Hibernate Migrates to JBoss Community

JBoss has just finished migrating Hibernate.org to the JBoss Community portal, where many other JBoss projects are housed.  The project pages have been transferred to the Magnolia instance and the community wiki is now on the Clearspace instance.  Aside...

0 replies - 15002 views - 03/20/10 by Mitchell Pronsc... in Daily Dose

Daily Dose - Hibernate 3.5 CR1 JPA 2 Compliant

Hibernate 3.5 CR1 JPA 2 Compliant  

0 replies - 18026 views - 02/15/10 by Mitchell Pronsc... in Daily Dose