Overview of Hibernate

Hibernate makes use of persistent objects commonly called as POJO (POJO = "Plain Old Java Object".) along with XML mapping documents for persisting objects to the database layer. The term POJO refers to a normal Java objects that does not serve any other special role or implement any special interfaces of any of the Java frameworks (EJB, JDBC, DAO, JDO, etc...).
Rather than utilize byte code processing or code generation, Hibernate uses runtime reflection to determine the persistent properties of a class. The objects to be persisted are defined in a mapping document, which serves to describe the persistent fields and associations, as well as any subclasses or proxies of the persistent object. The mapping documents are compiled at application startup time and provide the framework with necessary information for a class. Additionally, they are used in support operations, such as generating the database schema or creating stub Java source files.

Why Hibernate :
  • Hibernate was introduced to address the issues of Entity Beans
  • Hibernate is built on top of JNDI, JDBC, JTA
  • It uses XML based configuration files for mapping
  • Supports many databases like Sybase, Oracle, MySQL, other Object Oriented Databases etc.
  • Easy migration from one vendor database to another
  • Hibernate generates the JDBC Code based on the underlying vendor database
  • Hibernate APIs are very simple to learn and use
  • Provides quite powerful object query language known as Hibernate Query Language (HQL)
Hibernate Advantages:
  • Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code.
  • Provides simple APIs for storing and retrieving Java objects directly to and from the database.
  • If there is change in Database or in any table then the only need to change XML file properties.
  • Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects.
  • Hibernate does not require an application server to operate.
  • Manipulates Complex associations of objects of your database.
  • Minimize database access with smart fetching strategies.
  • Provides Simple querying of data.
Example - Java Class

    Public class Trade
     {
       Private Long tradeId;
       Private String clientId;
       Private String symbol;
       Private String orderType;
       Public Long getTradeId() { return id; }
       Private void setTradeId(Long id) { this.tradeId = id; }
       Public String getSymbol() { return symbol; }
       Public void setSymbol(String text) { this.symbol = text;}
     }


Hibernate Persistence Code

//Initialize Hibernate session
Session session = getSessionFactory().openSession();

//Start the transaction
Transaction tx = session.beginTransaction();

//Object to be persisted
Trade trade = new Trade();

//Set the object values
//Persist the Object
session.save(trade);

//Commit the transaction
tx.commit();

//Close the Hibernate Session
session.close();
….
How is Hibernate Persisting?

Hibernate used XML Mapping file to generate the SQL code to save the object

<hibernate-mapping>
<class name=“Trade" table=“Trades">
<id name=“tradeId" column=“TRADE_ID"></id>
<property name=“clientId" column=“CLIENT_ID"/>
<property name=“symbol" column=“SYMBOL"/>
<property name=“orderType" column=“ORDER_TYPE"/>
</class>
</hibernate-mapping>

Hibernate Generates SQL Statement like
INSERT INTO Trades (TRADE_ID, CLIENT_ID, SYMBOL, OR
DER_TYPE)
VALUES (30, “CL7678”, “IBM”, “M”)

RDBMS Table

Create Table Trades
(
            TRADE_ID int not null,
            CLIENT_ID varchar(50),
            SYMBOL varchar(15),
            ORDER_TYPE char(1)
)

            

JDBC Drivers & Architecture

JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for database access but in general JDBC Architecture consists of two layers:

JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases.

The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.

Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application:
Common JDBC Components:
The JDBC API provides the following interfaces and classes:

Driver Manager: This class manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.

Driver: This interface handles the communications with the database server. You will interact directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects.
Connection: This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only.

Statement: You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures.

ResultSet : These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data.

SQLException: This class handles any errors that occur in a database application.

                                                             What is JDBC Driver 
JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

For example, using JDBC drivers enable you to open database connections and to interact with it by sending SQL or database commands then receiving results with Java.

The Java.sql package that ships with JDK contains various classes with their behaviours defined and their actual implementaions are done in third-party drivers. Third party vendors implements thejava.sql.Driver interface in their database driver.

JDBC Drivers Types:
JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories,
Types 1, 2, 3, and 4, which is explained below:

Type 1: JDBC-ODBC Bridge Driver:

In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC requires configuring on your system a Data Source Name (DSN) that represents the target database.

When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available.

The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2: JDBC-Native API:
In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the database. These drivers typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine.

If we change the Database we have to change the native API as it is specific to a database and they are mostly obsolete now but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's overhead.

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java:
In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard network sockets to communicate with an middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.

This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can actually provide access to multiple databases.

You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client application. As a result, you need some knowledge of the application server's configuration in order to effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database, understanding the nuances will prove helpful.

Type 4: 100% pure Java:
In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself.

This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers.

Which Driver should be used?
Ø  If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.
Ø  If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver.
Ø  Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your database.
Ø  The type 1 driver is not considered a deployment-level driver and is typically used for development and testing purposes only.

                 For all java online training classes please contact : training@virtualnuggets.com
                                                        http://www.virtualnuggets.com/




INTRODUCTION TO JDBC

                                                             
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks commonly associated with database usage:
·         Making a connection to a database
·         Creating SQL or MySQL statements
·         Executing that SQL or MySQL queries in the database
·         Viewing & Modifying the resulting records

Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as:
·         Java Applications
·         Java Applets
·         Java Servlets
·         Java ServerPages (JSPs)
·         Enterprise JavaBeans (EJBs)

All of these different executables are able to use a JDBC driver to access a database and take advantage of the stored data.

JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code.

Establishing A Connection
The first thing to do, of course, is to install Java, JDBC and the DBMS on your working machines. Since we want to interface with an Oracle database, we would need a driver for this specific database as well. Fortunately, we have a responsible administrator who has already done all this for us on the Leland machines.

As we said earlier, before a database can be accessed, a connection must be opened between our program(client) and the database(server). This involves two steps:

·         Load the vendor specific driver
     Why would we need this step? To ensure portability and code reuse, the API was designed to be as independent of the version or the vendor of a database as possible. Since different DBMS's have different behavior, we need to tell the driver manager which DBMS we wish to use, so that it can invoke the correct driver.

An Oracle driver is loaded using the following code snippet:
                         Class.forName("oracle.jdbc.driver.OracleDriver")

·         Make the connection
     Once the driver is loaded and ready for a connection to be made, you may create an instance of a Connection object using:

   Connection con = DriverManager.getConnection(  "jdbc:oracle:thin:@dbaprod1:1544:SHR1_PRD",     username, passwd);

Okay, lets see what this jargon is. The first string is the URL for the database including the protocol (jdbc), the vendor (oracle), the driver (thin), the server (dbaprod1), the port number (1521), and a server instance(SHR1_PRD). The username and passwd are your username and password, the same as you would enter into SQLPLUS to access your account.

That's it! The connection returned in the last step is an open connection which we will use to pass SQL statements to the database. In this code snippet, con is an open connection, and we will use it below. 

Note:The values mentioned above are valid for our (Leland) environment. They would have different values in other environments.

Creating JDBC Statements

A JDBC Statement object is used to send your SQL statements to the DBMS, and should not to be confused with an SQL statement. A JDBC Statement object is associated with an open connection, and not any single SQL Statement. You can think of a JDBC Statement object as a channel sitting on a connection, and passing one or more of your SQL statements (which you ask it to execute) to the DBMS.

An active connection is needed to create a Statement object. The following code snippet, using our Connection object con, does it for you:

    Statement stmt = con.createStatement() ;

At this point, a Statement object exists, but it does not have an SQL statement to pass on to the DBMS. We learn how to do that in a following section.

Creating JDBC PreparedStatement

   Sometimes, it is more convenient or more efficient to use a PreparedStatement object for sending SQL statements to the DBMS. The main feature which distinguishes it from its superclass Statement, is that unlike Statement, it is given an SQL statement right when it is created. This SQL statement is then sent to the DBMS right away, where it is compiled. Thus, in effect, a PreparedStatement is associated as a channel with a connection and a compiled SQL statement.

The advantage offered is that if you need to use the same, or similar query with different parameters multiple times, the statement can be compiled and optimized by the DBMS just once. Contrast this with a use of a normalStatement where each use of the same SQL statement requires a compilation all over again.

PreparedStatements are also created with a Connection method. The following snippet shows how to create a parameterized SQL statement with three input parameters:

   PreparedStatement prepareUpdatePrice = con.prepareStatement(
      "UPDATE Sells SET price = ? WHERE bar = ? AND beer = ?");

Before we can execute a Prepared Statement, we need to supply values for the parameters. This can be done by calling one of the setXXX methods defined in the class Prepared Statement. Most often used methods are setInt, setFloat, setDouble, setString etc. You can set these values before each execution of   the prepared statement.

Continuing the above example, we would write:
   prepareUpdatePrice.setInt (1, 3);
   prepareUpdatePrice.setString (2, "Bar Of Foo");
   prepareUpdatePrice.setString (3, "BudLite");

Executing CREATE/INSERT/UPDATE Statements
 Executing SQL statements in JDBC varies depending on the ``intention'' of the SQL statement. DDL (data definition language) statements such as table creation and table alteration statements, as well as statements to update the table contents, are all executed using the method executeUpdate. Notice that these commands change the state of the database, hence the name of the method contains ``Update''.

The following snippet has examples of executeUpdate statements.
   Statement stmt = con.createStatement ();

   stmt.executeUpdate ("CREATE TABLE Sells” +
      "(bar VARCHAR2 (40), beer VARCHAR2 (40), price REAL)" );
   stmt.executeUpdate ("INSERT INTO Sells " +
      "VALUES ('Bar Of Foo', 'BudLite', 2.00)" );

   String sqlString = "CREATE TABLE Bars " +
      "(name VARCHAR2 (40), address VARCHAR2 (80), license INT)" ;
   stmt.executeUpdate (sqlString);


Since the SQL statement will not quite fit on one line on the page, we have split it into two strings concatenated by a plus sign(+) so that it will compile. Pay special attention to the space following "INSERT INTO Sells" to separate it in the resulting string from "VALUES". Note also that we are reusing the   same Statement object rather than having to create a new one.

          When executeUpdate is used to call DDL statements, the return value is always zero, while data modification statement executions will return a value greater than or equal to zero, which is the number of tuples affected in the relation.

While working with a Prepared Statement, we would execute such a statement by first plugging in the values of the parameters (as seen above), and then invoking the executeUpdate on it.

      int n = prepareUpdatePrice.executeUpdate() ;


Executing SELECT Statements
As opposed to the previous section statements, a query is expected to return a set of tuples as the result, and not change the state of the database. Not surprisingly, there is a corresponding method called executeQuery, which returns its results as a ResultSet object:

   String bar, beer;
   Float price;

   ResultSet rs = stmt.executeQuery ("SELECT * FROM Sells");
   While (rs.next() ) {
      Bar = rs.getString ("bar");
      Beer = rs.getString ("beer");
      Price = rs.getFloat ("price");
      System.out.println (bar + “sells " + beer + " for " + price + " Dollars.");
   }

The bag of tuples resulting from the query are contained in the variable rs which is an instance of ResultSet. A set is of not much use to us unless we can access each row and the attributes in each row. The ResultSetprovides a cursor to us, which can be used to access each row in turn. The cursor is initially set just before the first row. Each invocation of the method next causes it to move to the next row, if one exists and return true, or return false if there is no remaining row.

We can use the getXXX method of the appropriate type to retrieve the attributes of a row. In the previous example, we used getString and getFloat methods to access the column values. Notice that we provided the name of the column whose value is desired as a parameter to the method. Also note that the VARCHAR2 type bar, beer have been converted to Java String, and the REAL to Java float.

Equivalently, we could have specified the column number instead of the column name, with the same result. Thus the relevant statements would be:

      bar = rs.getString(1);
      price = rs.getFloat(3);
      beer = rs.getString(2);

While working with a Prepared Statement, we would execute a query by first plugging in the values of the parameters, and then invoking the execute Query on it.

                  ResultSet rs = prepareUpdatePrice.executeQuery () ;


                     For all java online training classes please contact : training@virtualnuggets.com
                                                      http://www.virtualnuggets.com/


Introduction to Swing

Introduction to Java/Swing

Java is commonly used for deploying applications across a network. Compiled Java code may be distributed to different machine architectures, and a native-code interpreter on eacharchitecture interprets the Java code. The core functions found in the Java interpreter are called the JFC (Java Foundation Classes). JFC provides generally useful classes, including classes for GUIs, accessability and 2D drawing. The original GUI classes in Java are known as AWT – the Abstract Windowing Toolkit. AWT provides basic GUI functions such as buttons, frames and dialogs, and is implemented in native code in the Java interpreter.

By contrast, Swing is not implemented in native code - instead it is implemented in AWT. Swing and AWT can (and normally do) coexist - we may use the buttons from Swing, alongside AWT event handlers.

·         A GUI component framework
o   A set of Java classes and interfaces for creating graphical interfaces
o   A follow-on to AWT
·         The Swing API provides:
o   A rich set of predefined components
o   A basis for creating sophisticated custom components

·         More flexible than AWT
·         Lets you:
o   Create non-rectangular components#
o   Combine components
o   Customize look & feel (L&F)
·         Sophisticated built-in features:
o   Tooltips
o   Borders and insets
o   Double-buffering for cleaner displays
o   Slow-motion graphics for debugging
·         Additional Swing APIs for:
o   Sophisticated text editing (e.g. HTML, RTF)
o   Undo/redo

The advantages of Swing are:

1. Consistent look-and-feel - The look and feel is consistent across platforms.
2. Pluggable look-and-feel - The look and feel can be switched on-the-fly.
3. High-level widgets - the Swing components are useful and flexible.
In general, the Swing components are easier to use than similar AWT components.

Swing programming

In this course I hope to clarify the general style of Swing applications, and show sufficient examples to build menu’d GUI applications with interesting graphical interactions. The same strategy was used in the introduction to Tcl/Tk. A good book that covers this material in detail is
   The JFC Swing Tutorial, by KathyWalrath and Mary Campione.

The toplevel components provided by Swing are:

1. JApplet - for applets within web pages
2. JDialog - for dialog boxes
3. JFrame - for building applications

All other Swing components derive from the JComponent class. JComponent provides

􀀀 Tool tips - little windows with explanations
􀀀 Pluggable look and feel - as described
􀀀 Layour management - items within the component
􀀀 Keyboard action management - Hot keys and so on.

And other facilities
Swing implements MVC architecture.

Pluggable look and feel


It is relatively easy to change the look and feel of an application - here are three:
If you wished to use the WinXX look-and-feel, in the main of your application, you can make
the following call:

UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

·         Hello World applet
o   Ordinary Applet
o   Contains Swing label, textfield & button
·         Illustrates:
o   Swing replacements for AWT components
o   Swing components added to an Applet
o   ToolTips

An equivalent Hello-world applet:

This code follows the same structure - it just instantiates a JLabel, and sets the text field, although in this code, the class extends a JApplet instead of a JFrame. When we compile and run this application we get a HelloWorldApp.class file, which has to be referenced in a web page:

The end result is:


For all java concepts online training please contact : training@virtualnuggets.com
                                   http://www.virtualnuggets.com/