Wednesday, December 21, 2011

Iflexion Java Business Layer

Monday, December 19, 2011

J2EE

J2EE Overview

Author : Exforsys Inc.     Published on: 6th Dec 2005    |   Last Updated on: 3rd Feb 2011

J2EE Overview

J2EE is a technology that aims to simplify the design and implementation of enterprise applications. In this tutorial you will learn what J2EE is, its benefits, J2EE main components, Evolution of Enterprise Application Frameworks, Why use J2EE, J2EE Platform Architecture, J2EE APIs and Technologies and J2EE Reference Implementation. Before continuing our J2EE discussion lets define what an enterprise application is.
Enterprise application is an application which probably has legacy existing applications and databases that you want to continue using them while adding or migrating to a new set of applications that exploit Internet, e-commerce and other new technologies.

Evolution of Enterprise Application Frameworks

The main reasons for the evolution of enterprise application frameworks are listed below:
• Need to attune new technologies especially improvements on web technologies
• Need to handle complex low level details inherent in enterprise applications like security, transaction processing and multi-threading.
• Evolution and popularity of widely accepted concepts like n-tier architectures and component based software development.
Several enterprise application frameworks have emerged based on the above listed needs. Some of the best known examples are Java2 Platform Enterprise Edition (J2EE) from Sun Microsystems, Distributed internet Applications Architecture (DNA) from Microsoft and Common Object Request Broker Architecture (CORBA) from Object Management Group (OMG).

Why use J2EE

J2EE may not be the perfect choice for developing enterprise applications. You should consider other alternatives before deciding to use J2EE. Some advantages of using J2EE for enterprise applications are listed below:
• Low level services are already implemented 
An enterprise application needs to implement very complex services to be successful. Some of those services are transaction and state management, resource pooling and multi-threading. J2EE architecture separates those low level services from the application logic. Since all those services are implemented by applications servers, you can save a lot of time if you need those services.

• J2EE is well documented and understood 
J2EE is developed by a consortium formed by several major companies in the industry. For more information on this consortium you can search for “Java Community Process” (see links section)

• J2EE is a standardized and reliable software architecture Using standardized and reliable software architecture in your development will most likely decrease your future costs and ensure longevity of your applications.

• J2EE gives you a lot of flexibility Once you develope your application with J2EE, you can deploy it wherever you need to. You can deploy your application to any application server with small changes.

• APIs used in J2EE are well documented. Several APIs are used to implement low level details of enterprise applications. Since those APIs are already written and well documented, this will save you a lot of time.

J2EE Platform Architecture

J2EE platform uses a multi-tiered distributed application model. Application logic is divided into components and each component is installed on a specific machine based on which tier that component resides.
Figure-1 J2EE Application Model
As you can see from the Figure-1, there are four tiers in J2EE application model: client tier, web tier, business tier and enterprise information system (EIS) tier. Business and web tiers are generally existed in a server application called application server or J2EE server. Application server provides complex services needed by components in business and web tiers.
Figure-2 Interaction between client, web and business tiers in J2EE
Client tier can have two types of components: web client or application client. Web clients access the components in the web tier namely servlets or java server pages (jsp). Web browsers as a web client are generally used to access web tier components.
Application clients are standalone applications that do not run in browsers (e.g. swing application). They directly accesses to the components in the business tier.
Figure-3 Business and EIS tiers
Figure-3 shows Business and EIS tiers in detail. EIS tier contains database and legacy systems and can be accessed from the business tier.
There are three types of components in business tier: entity beans, session beans and message-driven beans. We will discuss them separately in detailed subsequent tutorials.
Another important concept in J2EE architecture is the “container” concept. An enterprise application needs to implement very complex services to be successful. Some of those services are transaction and state management, resource pooling and multi-threading. J2EE architecture separates those low level services from the application logic by implementing those services in containers. So, web containers are mainly used to provide low level services to web components (e.g. servlet) or EJBs (e.g. entity beans) Containers are also used to manage execution of the components in business tier. Figure-4 may demystify this idea more.
Figure-4 J2EE Application Server and Containers

J2EE APIs and Technologies

There are several APIs and technologies which make J2EE a working platform. These APIs and technologies are described below briefly:
1. Java Database Connectivity (JDBC) API: JDBC is a set of interfaces which allows Java applications access to any database. This API has the same purpose as Microsoft’s ODBC.
2. Remote Method Invocation (RMI): RMI is an API which allows Java objects to communicate remotely with other objects. This API has the same purpose of CORBA from OMG.
3. Java IDL: IDL is a standard platform-independent declarative language which is used to define interfaces that object implementations provide and client objects call. Java IDL allows any Java object to communicate with other objects in any language by means of IDL.
4. Enterprise Java Beans: EJB is a standard distributed object framework and component model to Java. Enterprise Java Beans are components used in business tier of J2EE. The details and types of EJBs will be discussed in subsequent tutorials.
5. Servlets and Java Server Pages (JSP): Servlets are Java programs running on a web server and that produces results viewed remotely on a web server. Servlets and JSPs have the same purpose that CGI or PHP had in the past.
6. Java Message Service (JMS): JMS API is a messaging standard that allows J2EE components to create, send, receive, and read messages. It enables distributed communication between components.
7. Java Transaction API (JTA): JTA allows J2EE components to perform distributed transactions. Distributed transaction processing is a complex topic which is out of scope of this tutorial.
8. JavaMail: JavaMail API allows Java components send and receive emails in a platform-independent way.
9. Java API for XML Processing (JAXP): Extensive Markup Language (XML) is a data format for interchanging structured documents on the Web. JAXP allows Java applications to parse and transform XML documents. XML is heavily used in J2EE as a data format.
Ads
10. Java Naming and Directory Interface (JNDI): JNDI is a protocol which provides a standard API to access naming and directory services. Naming and directory services associate names with locations, services, information and resources. So, JNDI allows Java applications to find any necessary resource in a standard way.

J2EE Reference Implementation

J2EE reference implementation is the implementation of J2EE model described in the previous sections. It is freely available on the website of Sun. (see the links section) It includes Sun’s J2EE Application Server, a J2EE-compatible product for developing and deploying J2EE applications plus related development tools and documentation.
J2EE reference implementation is probably the best starting point for developing enterprise applications. But if you just plan to use web tier components (e.g. servlet and jsp), we recommend you to start with Tomcat.

Flex

With Web users expecting richer and more complex interfaces, Rich Internet Applications (RIAs) are seeing a huge increase in popularity. Adobe Flex is the tool of choice for many web developers when it comes to building RIAs.
Flex used to be one of those technologies that was only used by large corporate organisations — the first release of Flex was priced at around US$15,000 per CPU (a tad expensive for most developers) Since then, Flex has been released as open source software. Talk about a complete turnaround!
Flex is now in version 3.0, and runs on the Adobe Flash Player 9 runtime. Flex 3.0 has been such a success that Flex 4.0 has been announced for release in 2009. As a developer, getting in early and learning all you can now is a good idea — standing out in the Flex community will soon become extremely difficult.
Developers are picking up Flex with great speed. One of the reasons for this is that Flex programming is relatively easy to learn if you’re already familiar with XHTML. Of course, there’s always a transition period when you’re getting used to a new environment, but learning Flex won’t take long!
Another drawcard is that Flex applications can be developed to run on a user’s desktop thanks to the wonders of the Adobe AIR (Adobe Integrated Runtime) platform. Now you can develop and launch an RIA that runs in a web browser and as a desktop application. Deploying an application to a user’s desktop with Adobe AIR is easy — all that users need to do is click a link in the web browser to install the AIR runtime and your RIA on their machine. Now that’s quick deployment!
That’s enough rambling; let’s learn the basics of what Flex is all about.
WHY USE FLEX?
If you’re considering building a RIA, you have a few choices of technology, including Flex, Ajax, and Microsoft Silverlight. If you look at these options objectively, the development effort required for each (and the resulting user experience) is roughly the same. One of the benefits of Flex is its reach — the Adobe Flash Player, upon which Flex applications run, is already installed on about a billion computers wordwide!
Of course, Ajax also uses technologies that are installed on almost every computer in the world — JavaScript, XHTML, and CSS. One of the downfalls of Ajax, however, is that cross-browser compatibility can be difficult to achieve. What might work in one browser (for example, Firefox) might not work in another (such as Internet Explorer), so the debugging process has the potential to become difficult and long-winded.
Microsoft Silverlight, on the other hand, is similar to Flex in that it runs on a browser plugin. Silverlight, however, has yet to reach the installed userbase of the Flash player.
If you’re just starting out with building RIAs, you should definitely try all of them to see which one you like best and find easiest to work with — each of Flex, Silverlight and Ajax has its advantages and disadvantages. In my opinion, though, Flex is definitely the best RIA development technology available. Additionally, if you’re a fan of the Adobe Creative Suite, it’s good to know that many of these tools (Flash, Photoshop, Illustrator, Fireworks and so on) have Flex component integration built into them, which is a bonus no matter how you look at it.
OVERVIEW OF THE FLEX FRAMEWORK
A lot of people steer clear of the Flex framework because they think it’s complicated. But generally speaking, a framework is just a set of reusable classes that can work together to provide a base for an application.
Take a house as an analogy: every house on the planet has a framework. Each house has a foundation and walls, and those walls can’t stand without the foundation. Once the foundation has been laid and the walls are up, a roof can be applied and the interior designed and implemented, while work continues on the initial foundation.
If we apply this analogy to the Flex framework, we have a stack of logic — the controller logic — that has been made available for communicating with a database, handling security, writing to the file system, and so on. There are also the user interface elements — buttons, canvases, dropdown lists, and so on. All of these also form the foundation of your Flex application — the concrete slab, the timber beams and the bricks with which to build your house.
Flex is easy for web developers to learn because, at its core, it has a lot in common with (X)HTML, CSS, and JavaScript. Suppose you wanted to create a simple web page with a form button. In XHTML you’d type the following:
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <br>  
  2. <html xmlns="http://www.w3.org/1999/xhtml"> <br>  
  3.   <head> <br>  
  4.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <br>  
  5.     <title>Button Example</title> <br>  
  6.   </head> <br>  
  7.  <br>  
  8.   <body> <br>  
  9.     <form method="post" id="example" action="http://www.example.com/"> <br>  
  10.       <input type="button" name="newButton" id="newButton" value="This is a button" onclick="checkForm()" /> <br>  
  11.     </form> <br>  
  12.   </body> <br>  
  13. </html>  
When you view this markup in a web browser, you’ll see a button displayed with the label "This is a button".
The XHTML button
To display something similar in Flex we use a form of markup called MXML. Here’s the MXML markup for our previous example:
  1. <?xml version="1.0" encoding="utf-8"?> <br>  
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" <br>  
  3.     layout="absolute"> <br>  
  4.   <mx:Button x="10" y="10" label="This is a button" <br>  
  5.  id="newButton" <br>  
  6.       click="checkForm()"/> <br>  
  7.  <br>  
  8. </mx:Application>  

Saturday, December 17, 2011

Hibernate

Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style entity beans. Its mission back then was to simply offer better persistence capabilities than offered by EJB2 by simplifying the complexities and allowing for missing features.
Early in 2003, the Hibernate development team began Hibernate2 releases which offered many significant improvements over the first release.
JBoss, Inc. (now part of Red Hat) later hired the lead Hibernate developers and worked with them in supporting Hibernate. Hibernate is part of JBoss (a division of Red Hat) Enterprise Middleware System (JEMS) suite of products.

1. Introduction

Hibernate is an Object-relational mapping (ORM) tool. Object-relational mapping or ORM is a programming method for mapping the objects to the relational model where entities/classes are mapped to tables, instances are mapped to rows and attributes of instances are mapped to columns of table.
A “virtual object database” is created that can be used from within the programming language.
Hibernate is a persistence framework which is used to persist data from Java environment to database. Persistence is a process of storing the data to some permanent medium and retrieving it back at any point of time even after the application that had created the data ended.

2. Hibernate Architecture

hibernate-architecture-mini
The above diagram shows minimal architecture of Hibernate. It creates a layer between Database and the Application. It loads the configuration details like Database connection string, entity classes, mappings etc.
Hibernate creates persistent objects which synchronize data between application and database.
hibernate-architecture-compre
The above diagram shows a comprehensive architecture of Hibernate. In order to persist data to a database, Hibernate create an instance of entity class (Java class mapped with database table). This object is called Transient object as they are not yet associated with the session or not yet persisted to a database. To persist the object to database, the instance of SessionFactory interface is created. SessionFactory is a singleton instance which implements Factory design pattern. SessionFactory loads hibernate.cfg.xml file (Hibernate configuration file. More details in following section) and with the help of TransactionFactory and ConnectionProvider implements all the configuration settings on a database.
Each database connection in Hibernate is created by creating an instance of Session interface. Session represents a single connection with database. Session objects are created from SessionFactory object.
Hibernate also provides built-in Transaction APIs which abstracts away the application from underlying JDBC or JTA transaction. Each transaction represents a single atomic unit of work. One Session can span through multiple transactions.

2.1 SessionFactory (org.hibernate.SessionFactory)

A thread-safe, immutable cache of compiled mappings for a single database. A factory for org.hibernate.Session instances. A client of org.hibernate.connection.ConnectionProvider. Optionally maintains a second level cache of data that is reusable between transactions at a process or cluster level.

2.2 Session (org.hibernate.Session)

A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC java.sql.Connection. Factory for org.hibernate.Transaction. Maintains a first level cache of persistent the application’s persistent objects and collections; this cache is used when navigating the object graph or looking up objects by identifier.

2.3 Persistent objects and collections

Short-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one org.hibernate.Session. Once the org.hibernate.Session is closed, they will be detached and free to use in any application layer (for example, directly as data transfer objects to and from presentation).

2.4 Transient and detached objects and collections

Instances of persistent classes that are not currently associated with a org.hibernate.Session. They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed org.hibernate.Session.

2.5 Transaction (org.hibernate.Transaction)

(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A org.hibernate.Session might span several org.hibernate.Transactions in some cases. However, transaction demarcation, either using the underlying API or org.hibernate.Transaction, is never optional.

2.6 ConnectionProvider (org.hibernate.connection.ConnectionProvider)

(Optional) A factory for, and pool of, JDBC connections. It abstracts the application from underlying javax.sql.DataSource or java.sql.DriverManager. It is not exposed to application, but it can be extended and/or implemented by the developer.

2.7 TransactionFactory (org.hibernate.TransactionFactory)

(Optional) A factory for org.hibernate.Transaction instances. It is not exposed to the application, but it can be extended and/or implemented by the developer.

3. Hibernate Configuration

Hibernate configuration is managed by an instance of org.hibernate.cfg.Configuration. An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application’s Java types to an SQL database. The org.hibernate.cfg.Configuration is used to build an immutableorg.hibernate.SessionFactory. The mappings are compiled from various XML mapping files or from Java 5 Annotations.
Hibernate provides following types of configurations
  1. hibernate.cfg.xml – A standard XML file which contains hibernate configuration and which resides in root of application’s CLASSPATH
  2. hibernate.properties – A Java compliant property file which holds key value pair for different hibernate configuration strings.
  3. Programmatic configuration – This is the manual approach. The configuration can be defined in Java class.

3.1 hibernate.cfg.xml

This is an alternate way of configuring hibernate. The hibernate.cfg.xml file is a standard XML file which contains all the configuration parameters like database connection, class mappings etc. This file needs to be placed root of CLASSPATH of application.
Below is the sample hibernate.cfg.xml file:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
    <!-- a SessionFactory instance listed as /jndi/name -->
    <session-factory
        name="java:hibernate/SessionFactory">
 
        <!-- properties -->
        <property name="connection.datasource">java:/comp/env/jdbc/MyEmployeeDB</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">false</property>
        <property name="transaction.factory_class">
            org.hibernate.transaction.JTATransactionFactory
        </property>
        <property name="jta.UserTransaction">java:comp/UserTransaction</property>
 
        <!-- mapping files -->
        <mapping resource="net/viralpatel/hibernate/Employee.hbm.xml"/>
        <mapping resource="net/viralpatel/hibernate/Department.hbm.xml"/>
 
        <!-- cache settings -->
        <class-cache class="net.viralpatel.hibernate.Employee" usage="read-write"/>
        <class-cache class="net.viralpatel.hibernate.Department" usage="read-only"/>
        <collection-cache collection="net.viralpatel.hibernate.Department.employees" usage="read-write"/>
 
    </session-factory>
 
</hibernate-configuration>
Once the hibernate.cfg.xml file is created and placed in root of application’s CLASSPATH, the same can be loaded in Hibernate using following API.
1
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
This above code will load default hibernate.cfg.xml file and all the configuration mentioned in it.
In case you want to override default naming convention and want to have your own configuration file like “employeedb.cfg.xml”, following API can be used:
1
2
3
SessionFactory sf = new Configuration()
    .configure("employeedb.cfg.xml")
    .buildSessionFactory();

Note: Both hibernate.cfg.xml and hibernate.properties files can be provided simultaneously in an application. In this case hibernate.cfg.xml gets precedence over hibernate.properties.

3.2 hibernate.properties

This is the easiest way to get started with Hibernate. Create a file hibernate.properties and place it in root of your applications CLASSPATH.
Below is the sample hibernate.properties file:
01
02
03
04
05
06
07
08
09
10
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url= jdbc:mysql://localhost:3306/employee
hibernate.connection.username=root
hibernate.connection.password=swordfish
hibernate.connection.pool_size=1
hibernate.transaction.factory_class = \
    org.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class = \
    org.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = org.hibernate.dialect.MySQLDialect
For detail description of Configuration parameters, refer this article Hibernate configuration properties.

3.3 Programmatic configuration

We can obtain a org.hibernate.cfg.Configuration instance by instantiating it directly and specifying XML mapping documents. If the mapping files are in the classpath, use addResource(). For example:
1
2
3
Configuration cfg = new Configuration()
    .addResource("Employee.hbm.xml")
    .addResource("Department.hbm.xml");
An alternative way is to specify the mapped class and allow Hibernate to find the mapping document for you:
1
2
3
Configuration cfg = new Configuration()
    .addClass(net.viralpatel.hibernate.Employee.class)
    .addClass(net.viralpatel.hibernate.Department.class);
Hibernate will then search for mapping files named /net/viralpatel/hibernate/Employee.hbm.xml and /net/viralpatel/hibernate/Department.hbm.xml in the classpath. This approach eliminates any hardcoded filenames.
A org.hibernate.cfg.Configuration also allows you to specify configuration properties. For example:
1
2
3
4
5
6
Configuration cfg = new Configuration()
    .addClass(net.viralpatel.hibernate.Employee.class)
    .addClass(net.viralpatel.hibernate.Department.class)
    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
    .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
    .setProperty("hibernate.order_updates", "true");

4. Building a SessionFactory

Once the instance of org.hibernate.cfg.Configuration is created using any of the above method, the singleton instance of SessionFactory can be created as follow:
1
SessionFactory sessions = cfg.buildSessionFactory();
Hibernate does allow your application to instantiate more than one org.hibernate.SessionFactory. This is useful if you are using more than one database.

5. Getting Session instance

As noted above, Session represents a communication channel between database and application. Each session represents a factory of transactions. Session can be created from SessionFactory as follows:
1
Session session = sessions.openSession(); // get a new Session
Thus, in this article we saw an overview of Hibernate ORM and its architecture. Also we noted its different components like SessionFactory, TransactionFactory, Session etc and APIs to instantiate these objects in your application.
In next tutorial, We will write a Hello World Hibernate program using both XML file based configuration and Annotations.
Stay tuned! :)