Wednesday, July 25, 2007

Are You Using Abstract Classes, Polymorphism, and Interfaces?

Are You Using Abstract Classes, Polymorphism, and Interfaces?
If the answer is no, at a minimum your project needs a code review.

Let's work on the following assignment: a company has employees and consultants. Design classes with and without the use of inheritance to represent the people who work for this company. The classes should have the following methods:

* changeAddress
* promote
* giveDayOff
* raiseSalary

Promotion means giving one day off and raising the salary by a specified percentage. For employees, the method raiseSalary should raise the yearly salary and, for consultants, it should increase their hourly rate.

Abstract Classes
A class is called abstract if it has at least one abstract (not implemented) method. The keyword abstract has to be placed in the definition of the method(s) and the class itself. For example, the class in Listing 1 has three concrete methods and one abstract. (Listings 1-11 are available over here)

Abstract classes cannot be instantiated, but they allow you to create superclasses that implement some of the functionality, while leaving one or more methods to be implemented in subclasses.

The class Person can contain dozens of concrete methods that are the same for every person, such as changeAddress and giveDayOff, but since the process of raising a salary is different for employees and consultants, the method raiseSalary should remain abstract. Please note that even though this method is abstract, it could be called in an abstract class because by the time the concrete class is instantiated, the method will be already implemented. Since we have two types of workers, let's create subclasses Employee and Consultant and implement the method raiseSalary based on different rules (see Listings 2 and 3).

The designer of the class Person may not know the specifics of the raising salary process, but this does not stop him or her from calling the method raiseSalary. Programmers writing subclasses are forced to write an implementation of this method according to its signature declared in the abstract class. If they declare a method raiseSalary with a different argument list, this will be considered method overloading and the subclass will remain abstract. The class Promoter in Listing 4 shows how to use the classes Employee and Consultant for promoting workers.

Polymorphism
A programming language could be considered object-oriented if it supports inheritance, encapsulation, and polymorphism. The first two notions can be easily defined:

* Inheritance lets you design a class by deriving it from an existing one. This feature allows you to reuse existing code without doing copy and paste. Java provides the keyword extends for declaring inheritance.
* Encapsulation is the ability to hide and protect data. Java has access-level qualifiers such as public, private, and protected to control who can access class variables and methods. There is also so-called package-level protection, which is automatically engaged if you don't use any of the access-level keywords.
* Polymorphism, though, is easier to understand through an example. Let's look at the classes Person, Employee, and Consultant from a different angle. We'll populate a Vector, mixing up the instances of classes Employee and Consultant - in real life this information usually comes from a database. For example, a program could get the person's work status from the database and instantiate an appropriate concrete class. The class Promoter (see Listing 4) will give an additional vacation day and increase the salary or hourly rate of every worker by 5%.

Please note that even though we cast every object from the collection workers to the ancestor's type Person in line 17, Listing 4, the variable pers can hold references to its descendent objects. The actual object type will be evaluated during runtime only. This feature of object-oriented languages is called runtime or late binding.

The output of the class Promoter will look as follows:

Class Person: Promoting a worker...
Class Person: Adding a day off
Class Employee:Increasing salary by 5%
Class Person: Promoting a worker...
Class Person: Adding a day off
Class Consultant: Increasing hourly rate by 5%
Class Person: Promoting a worker...
Class Person: Adding a day off
Class Employee:Increasing salary by 5%
Class Person: Promoting a worker...
Class Person: Adding a day off
Class Employee:Increasing salary by 5%

Both classes Employee and Consultant are inherited from the same base class Person. Instead of having different methods for increasing the worker's compensation based on its type, we give a polymorphic behavior to the method raiseSalary, which applies different business logic depending on the type of object from the collection. Even though it looks as if we're calling the same method promote, this is not the case. Since the actual object type is evaluated during runtime, the salary is raised properly according to this particular object's implementation of the method raiseSalary. This is polymorphism in action.

The while loop in the class Promoter will remain the same even if we add some other types of workers inherited from the class Person. For example, to add a new category of worker - a foreign contractor - we'll have to create a class Foreign- Contractor derived from the class Person and implement the method raiseSalary there. The class Promoter will keep casting all these objects to the type Person during runtime and call the method raiseSalary of the proper object.

Polymorphism allows you to avoid using switch or if statements with the expensive operator instanceof. Listing 5 shows an ugly alternative to our while loop from the class Promoter that assumes there is no abstract method raiseSalary, but we have separate promote methods in each subclass of the Person. This code would work slower than the polymorphic version from the class Promoter, and the if statement would have to be modified every time a new type of worker is added.

Interfaces
A similar functionality could be implemented using Java interfaces. We'll keep working with a modified version of the ancestor class Person because it has such useful methods as changeAddress and giveDayOff. But this class doesn't have to be abstract anymore because the method raiseSalary will be moved to a Java interface. The method promote won't be needed; we'd rather make the method giveDayOff available to descendants of the class Person by changing the private access level to protected (see line 8 in Listing 6).

Here's the "interface way" to ensure that each person in the firm receives the proper salary raise despite the differences in payroll calculation.

Let's define an interface Payable in Listing 7. More than one class can implement this interface (see Listing 8). When the class Consultant declares that it implements interface Payable, it promises to write implementations for all methods declared in this interface - in our case it's just one method raiseSalary. Why is it so important that the class will "keep the promise" and implement all the interface's methods? In many cases interface is a description of some behavior. In our case behavior Payable means the existence of the method boolean raiseSalary(int percent). If any other class knows that Employee implements Payable, it can safely call any method declared in the Payable interface (see the interface example in Listing 9).

Let's forget for a moment about employees and consultants and switch to the Java AWT listeners and events. When a class declares that it implements the interface java.awt.Action- Listener, a JVM will call the method actionPerformed on this class whenever the user clicks on the window's button, and in some other cases as well. Try to imagine what would happen if you forgot to include the method actionPerformed in your class. The good news is that your class won't even compile if not all methods declared in the interface were implemented. The java.awt.WindowListener interface declares seven methods, and even if you are interested only in the windowClosing one, you must include six additional empty-bodied methods to compile the class (window adapters simplify this process, but they are beyond the scope of this article).

While both abstract classes and interfaces can ensure that a concrete class will have all required methods, abstract classes can also contain implemented methods, but interfaces can't.

Beside method declarations, interfaces can contain final static variables. For example, let's say we have multiple bonus-level codes used in several classes during the calculation of new salaries. Instead of redefining these constants in every class that needs them, we can create the interface shown in Listing 10.

Now a small change in the class declaration will allow us to use these bonus levels as if they were declared in the class Employee:

public class Employee
implements Payable, Bonus {
S
if (empLevel==JUNIOR_LVL){
//apply the rules for juniors
}
}

public class Consultant
implements Payable, Bonus {
S
}

Java does not allow multiple inheritance, which means a class can't have two independent ancestors, but you can use interfaces as a workaround. As you've seen in the example above, a class can implement multiple interfaces; it just needs to implement all methods declared in all interfaces. If your window needs to process button clicks and window closing events, you can declare a class as follows:

class MyWindow implements ActionListener, WindowListener{S}

During evolution, an Employee can obtain multiple behaviors, for example

class Employee extends Person
implements Payable, Transferable,
Sueable, Bonus {S}

Consultants such as myself are usually more primitive creatures and can be defined as follows:

class Consultant extends Person
implements Payable, Sueable {S}

But if a program such as Promoter is interested only in Payable functions, it can cast the object only to those interfaces it intends to use, for example:

Employee emp = new Employee();
Consultant con = new Consultant();
Payable person1 = (Payable) emp;
Payable person2 = (Payable) con;

Now we're ready to write a second version of the class Promoter that will use the classes Employee and Consultant defined in Listings 8 and 11.

The output of this program will look similar to the output of the class Promoter from Listing 4:

Class Employee:Increasing salary by 5%
Class Consultant: Increasing hourly rate by 5%
Class Employee:Increasing salary by 5%
Class Employee:Increasing salary by 5%

Line 18 of Listing 9 may look a little confusing: How can we call a concrete method raiseSalary on a variable of an interface type? Actually we call a method on a concrete instance of the Employee or a Consultant, but by casting this instance to the type Payable we are just letting the JVM know that we're only interested in the methods that were declared in this particular interface.

Java Technical Interviews
During the technical interviews, probably the most frequently asked question is, "What's the difference between Java abstract classes and interfaces?"

During the job interview your answers should be clear and short; you won't even have a chance to use all the material presented here. Here's one version of the answer to our problem.

If two classes have lots of common functionality, but some methods should be implemented differently, you could create a common abstract ancestor Person and two subclasses Employee and Consultant. The method raiseSalary must be declared abstract in the class Person while other methods should be concrete. This way we ensure that the subclasses do have the method named raiseSalary with a known signature, so we could use it in the ancestor without knowing its implementation. Java interfaces should also be considered in cases when the same method must be implemented in multiple classes - in this case we do not need to use abstract ancestors. Actually, interfaces could be your only option if a class already has an ancestor that can not be changed.

One good interview technique is to impress the interviewer by elaborating on a related topic. Discussion of abstract classes and interfaces gives you a good opportunity to show your understanding of polymorphism.

Summary
Use of abstract classes, interfaces, and polymorphism improves the design of any project by making it more readable and easily extensible. This also makes your code more compact and elegant.

source:

Monday, July 16, 2007

Polymorphism -I





Polymorphism is an often-misunderstood concept within the developer community. Outside the community it's often a buzzword used to create an image of intellectual capital accumulating in a vault somewhere. This article will attempt to define, in a very basic way: What polymorphism is What types of polymorphism exist How they can benefit the Java developer and architect in building better systems What Is Polymorphism? Polymorphism is the ability of one object to be treated, or used, like another. In their ACM report Cardelli and Wegner detailed the types of polymorphism and their relationship to each other. To illustrate this relationship, they created the diagram shown below.









Polymorphism is a powerful tool in the developer's arsenal, allowing architectures to be designed and built that will be flexible enough to change with businesses' needs, yet stable enough not to require redesign and rebuild on a regular basis. Since approximately 80% of the cost of software is for maintenance, building polymorphic architectures can greatly reduce the overall cost of developing good software.
Why Should I Care? Polymorphism is extremely useful in designing enterprise-level systems, as you can create and define multiple interface layers that allow outside parties or outside software to interact with your system in a particular way. We all know how helpful it is in system integration to have a published API, but if interior system changes become necessary, the API may have to be republished and integrated systems may have to be reworked. To avoid this, careful consideration should be given to object APIs as well as the overall system APIs during design. One way to ensure that a robust system can deal with objects that have more complex methodologies than were originally intended is to have the object API be polymorphic. This way, the system knows a "face" of the object being passed to it, but doesn't have to be aware of extemporaneous changes.
Types of Polymorphism What follows are some simple examples of polymorphism as it relates to a video game environment. These examples are used to further define and illustrate the different types of polymorphism.
Overloading Overloading polymorphism occurs when a child class overrides the method implementation of the parent class. This type of polymorphism is used when different child classes have different behaviors based on some intrinsic characteristic of the child class. As an example, if milk and vodka are both drink objects, both will have a method called ingest. The results of ingesting milk and vodka are extremely different, but when designing a character for a game, the only thing you'd need to be concerned about is ingesting the drink and displaying the results. This is a very simple example of overloading polymorphism, since each subclass is redefining the ingest method to return results for its particular class type (see Listing 1).
Inclusion Inclusion polymorphism occurs if a child class inherits its method substance from the base or parent class. This enables objects or systems that would previously have used the base class to use the child classes with equivalent results. Inclusion polymorphism is most useful in masking the inherent complexities of child classes from objects or systems that previously dealt with the parent class. As an example, if the drinks in question were water and Perrier, they might share the ingest method from the base class of drink. This would be an example of inclusion or subclassing polymorphism. Regardless of whether the polymorphism in this example is overloading or inclusion, your character in the game only needs to be concerned with ingesting the drink and dealing with the results.
public Class Water extends Drink{public Water(){}}public Class Perrier extends Drink{public Perrier(){}}
Overloading and inclusion are the most common types of polymorphism in Java (along with special cases of overloading polymorphism that relate to interfaces, which we'll discuss later). Parametric and coercion polymorphisms are also used in Java, but to a lesser degree in most implementations.
Relationship Between Inclusion and Overloading Polymorphism Inclusion polymorphism exists when several subclasses use the method of the superclass (parent) to perform whatever action is required.
Overloading polymorphism exists when each subclass defines its own method of action, either because the parent class has declared the method abstract, or because it simply wishes to provide special processing.
Parametric Parametric polymorphism occurs when a class or classes implement methods that are the same in signature except for the parameters passed to the method. This is extremely useful, as one class can handle a great many different types of arguments to a specific method, enabling the class to be used as a bridge between the different types of objects that wish to communicate with your system and the system itself. An example of parametric polymorphism would be if an ElectromagneticRailGun class had multiple methods for fireProjectile - say, one that took a chunk of iron ore and one that took a missile. The results of firing the projectile would be very different depending on the type of projectile that was fired.
public Class ElectromagneticRailGun{public String fireProjectile(IronOre chunk){ return new String("Boy that smarts!");}public String fireProjectile(Missile icbm){return new String("Global Thermonuclear War");}}
Coercion Coercion polymorphism occurs when a primitive or object type is cast or "coerced" into being another primitive type or object type. An example of coercion polymorphism would be if the character display in the game always showed the number of rounds left in the current weapon, but an energy gun might actually measure the amount of charge left in less than one unit increments, say, 42.3. A revolver, on the other hand, might show five bullets left. But the display only shows whole numbers. So, when updating the display for the energy weapon, we might use casting to change the float value of 42.3 to an integer value of 42. This is usually inefficient, and always dangerous since you're losing precision, but it's sometimes necessary.
public Class Display extends java.awt.Label{public Display(){super();}public setBulletsLeft(int in){super.setText(String.valueOf(in));}public setEnergy(float units){setBulletsLeft((int)units);}}
This is usually a really bad idea, and may result in casting exceptions thrown at runtime. A safer way to convert primitive values in Java is to use the conversion interfaces defined with the language itself. The code above can be rewritten to include this methodology as follows:
public Class Display extends java.awt.Label{public Display(){super();}public setBulletsLeft(int in){super.setText(String.valueOf(in));}public setEnergy(float units){public Float f = new Float(units);setBulletsLeft(f.intValue());}}
Object coercion is a larger and more difficult subject, and won't be detailed here. If a Class coercion situation occurs, consider using the instanceof keyword to provide safer, more stable implementations.
public class Processor{public Processor(){}public void process(Parent p){if (p instanceof Child1){//do something}else{//do something else}}}
Multiple Inheritance vs Interfaces In Java there's a special type of overloading polymorphism to examine. It comes about because of the addition of interfaces to the Java language. An interface is usually defined in a separate file, and specifies the API of the object that will implement the interface.
When Java was first introduced, a lot of C++ programmers were concerned by the lack of multiple inheritance in Java. In some OO languages, such as C++, multiple inheritance is allowed. In Java we have only single inheritance, that is, any class can extend only one parent class. A lot of people starting out in Java see this as a handicap, but they usually change their minds once they understand the power of interfaces.
It's possible to use implementation of interfaces to achieve multiple inheritance. Interfaces in Java don't really allow multiple inheritance, since all classes that implement an interface must implement all methods declared by the interface, just as all classes that subclass a parent must implement all abstract methods declared in the parent class or declare them abstract themselves. Interface implementation does allow for a rather unique type of inclusion polymorphism, however. Since any method can take an interface type as an argument, the method can always be sure that whatever kind of object it's receiving will have all the methods declared in the interface, and they will always return the required type of response. Since a class can implement multiple interfaces, the ability of any object to be utilized by multiple methods increases geometrically as the number of interfaces it implements and the number of methods that accept that interface as a parameter type increase.
To use our video game example, molten metal could implement the drinkable interface just as the drink class does, but the results would be drastically different.
public Class MoltenMetal implements Drinkable{public MoltenMetal();public String ingest(){return new String("ouch!!");}}
Parametric Polymorphism in E-Commerce Situations Often in building a fairly robust system you want to expose parts of the API to the general public. You might wish to have logging methods that took the object where the error occurred, or a String containing the error message to be stored or an Exception that would denote what kind of problem occurred. These types of method signatures might look something like:
static public void log(Object o, int level)static public void log(String o, int level)static public void log(Exception e, int level) So sending data to the log, with either the object causing the problem (or a message about the problem) or the Exception that was generated would yield applicable results.
Inclusion Polymorphism in E-Commerce Situations Inclusion polymorphism is used in e-commerce situations to design and build robust systems that don't require major modification when the highly volatile market changes. In designing and building a transaction server, you might want to build one that processes Transaction Data Objects (TDO). But you might need to create new types of TDOs depending on the type of transaction you wished to process. The beauty of inclusion polymorphism in this situation is that the transaction server code would never change, and any class that extended TDO could be passed to the transaction server for processing.
public Class TDO{public TDO(){}//some transaction methods}public class TransactionServer{public TransactionServer(){}public void process(TDO trans){//transaction processing code}}
Overloading Polymorphism in E-Commerce Situations As discussed earlier, interfaces allow for a special type of overloading polymorphism in Java. This becomes extremely useful when we consider that we've built our transaction server and now we want to run it in a CORBA environment. We can use the declared interfaces of our services and extend the base classes supplied by (or created via a tool by) the ORB vendor, and we've got instant CORBA-compliant objects.
Overloading is also useful if you have a specific type of processing that each subclass needs to do, but a lot of "overhead" processing that all classes of that type need to do. As an example, you can declare an abstract method called process in your Base servlet class, which gets called whenever you get a Post request. When you extend the Base class, all the child classes can then process the request in their own way. The base class can contain all the methods to set the return type, put headers and footers into the response, set up connections, read parameter files and do all the other "housekeeping" chores. That way, when you need to create a new servlet, you simply extend the base class and implement one method containing your business logic.
Coercion - There's Usually a Better Way Coercion has limited use in most production environments, due to the dangers of losing precision and possibly a ClassCastException at runtime. If you often find yourself using casting, try using the object translation methodologies mentioned previously or try creating the most generic situation possible, then using the instanceof keyword to determine the actual type of object you're dealing with for specific processing.

Thursday, July 12, 2007

Penelope Cruz -I


Penelope Cruz -I

Wednesday, July 11, 2007

catherine zeta jones - I







catherine


Tuesday, July 10, 2007

Penelope



Monday, July 9, 2007

Penelope Cruz



Polymorphism

Polymorphism
• A variable of a superclass type can reference an object of a subclass type.
Computer myComp, yourComp;
// what exactly is happening in RAM at this point?
myComp = new Computer(arg list);
yourComp = new Laptop(arg list);
• Polymorphism means many forms or many shapes
• Polymorphism allows the JVM to determine which method to invoke at run time
• At compile time, the Java compiler can’t always determine what type of object a superclass may reference but it will be known at run time

Example of polymorphism
• Suppose we declare an object of type Computer
• Then we ask the user if they have a desktop or laptop
• If it is a desktop, we use the Computer constructor
• If it is a laptop, we use the Laptop constructor.
• Only when a constructor is called is space set aside on the heap to store the information for the object.
• Until execution, the actual dynamic type is unknown. This is called late binding.

Using polymorphism
• Suppose we declare an arrays of Computers,
– then fill the array with computers in a certain lab,
– some of which are laptops, some desktops
Computer [ ] labComp = new Computer[10]
• Then when we loop through the array
– we can call toString for each computer in the array, and the method for the type will be called

Abstract classes & methods
• Sometimes you want to require that all subclasses override a method
– Example: a print method, where what is to be printed varies among sublclasses
• This is, in essence, requiring all subclasses to implement behavior that is only being specified (not implemented) in the superclass.
• The abstract keyword is used in this case
public abstract void print( );
Classes can be abstract, as well as methods.

Polymorphism: another look
• Polymorphism means that there are a number of different subclasses of objects that will respond to the same message
• Example: Shape superclass
• and Circle, Square, Triangle subclasses that inherit all the methods and data members of Shape
• One of the things we would like to do with all our Shape classes is to find the area of each
• So in class Shape we want a method findArea( ) to be sure that all the subclasses override it.
– But what is the formula to find the area of a shape?
– Since we don’t know, we cannot implement the method findArea( )
– This makes it an Abstract method: i.e. no implementation
– Any class that contains an abstract method is an abstract class.

Declaring abstract methods or classes
• public abstract class Shape
{ private double side; // data field

public abstract double findArea( );
// note semicolon & no implementation
} // end class Shape


Declaring objects of a subclass
• An object of type Circle, Square, or Triangle is also, by inheritance, of type Shape
• In main, where we instantiate object to use the Shape classes, we could declare three object of type shape
Shape cir, squar, tri;
• Then to instantiate each object, we must call their constructors
cir = new Circle(args);
squar = new Square(args);
tri = new Triangle( args);
• Now we could declare an array of shapes, some of which are circles, some triangles, and some squares
– When we loop through the array, we call findArea( ) for each object, and automatically, the correct findArea( ) method is called for each shape.
• This, then is polymorphism: one call to findArea( ) results in different behavior depending on the type of each object.

Interfaces in Java
• A Java subclass can be derived from only one superclass (no multiple inheritance)
• Sometimes you would like to have several classes have a common interface (i.e. implement all the same methods), but also inherit from a superclass.
– This is an alternative to multiple inheritance
• An interface is similar to a class definition in that it includes the definition of methods
– But an interface cannot be instantiated
• You can derive a class from an interface, and if you implement ALL the required methods, you can instantiate that class.

Concrete & Abstract classes
• An abstract class is one that has at least one abstract method
– It is provided only to have other classes derived from it
– An object of this class cannot be instantiated
• A concrete class is has no abstract methods
– If you declare a subclass of an abstract class, and do not implement its abstract methods, you will get a compiler error

Abstract Classes and Interfaces
• Abstract classes are much like Interfaces, in that they both may have methods that are not implemented.
• One difference is that some of the methods of an abstract class can be implemented,
– while no methods of an Interface can be implemented
• Another difference is that abstract classes can define instance variables
– Interfaces cannot do this.

Abstract Class Number and the Java Wrapper Classes
• The abstract class Number has as its subclass all the wrapper classes for primitive numeric types
• A wrapper class is used to store a primitive-type value in an object type
• Each wrapper class contains constructors to create an object that stores a particular primitive value
• A wrapper class has methods for converting the value stored in a different numeric type
• Look at the Java API for the Number class

Hibernate Tutorial

Hibernate tutorial



1. Introduction

Hibernate; the latest Open Source persistence technology at the heart of J2EE EJB 3.0 is available for download from Hibernet.org.TheHibernate core is 68,549 lines of Java code together with 27,948 lines of unit tests, all freely available under the LGPL, and has been in development for well over a year.

Hibernate, maps the Java classes to the database tables. It also provides the data query and retrieval facilities that significantly reduce the development time. Hibernate is not the best solutions for data centric applications that only uses the stored-procedures to implement the business logic in database. It is most useful with object-oriented domain modes and business logic in the Java-based middle-tier. Hibernate allows transparent persistence that enables the applications to switch any database. Hibernate can be used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans.

1.1 Features
  • Hibernate 3.0 provides three full-featured query facilities: Hibernate Query Language, the newly enhanced Hibernate Criteria Query API, and enhanced support for queries expressed in the native SQL dialect of the database.
  • Filters for working with temporal (historical), regional or permissioned data.
  • Enhanced Criteria query API: with full support for projection/aggregation and subselects.
  • Runtime performance monitoring: via JMX or local Java API, including a second-level cache browser.
  • Eclipse support, including a suite of Eclipse plug-ins for working with Hibernate 3.0, including mapping editor, interactive query prototyping, schema reverse engineering tool.
  • Hibernate is Free under LGPL: Hibernate can be used to develop/package and distribute the applications for free.
  • Hibernate is Scalable: Hibernate is very performant and due to its dual-layer architecture can be used in the clustered environments.
  • Less Development Time: Hibernate reduces the development timings as it supports inheritance, polymorphism, composition and the Java Collection framework.
  • Automatic Key Generation: Hibernate supports the automatic generation of primary key for your table
  • EJB3-style persistence operations: EJB3 defines the create() and merge() operations, which are slightly different to Hibernate's saveOrUpdate() and saveOrUpdateCopy() operations. Hibernate3 will support all four operations as methods of the Session interface.
  • Hibernate XML binding enables data to be represented as XML and POJOs interchangeably.
  • The EJB3 draft specification support for POJO persistence and annotations.

Hibernate Architecture


The above diagram shows that Hibernate is using the database and configuration data (properties and xml mapping) to provide persistence services (and persistent objects) to the application.

To use Hibernate, it is required to create Java classes that represents the table in the database and then map the instance variable in the class with the columns in the database. Then Hibernate can be used to perform operations on the database like select, insert, update and delete the records in the table. Hibernate automatically creates the query to perform these operations.

Hibernate architecture has three main components:

  • Connection Management: - Hibernate Connection management service provide efficient management of the database connections. Database connection is the most expensive part of interacting with the database as it requires a lot of resources of open and close the database connection.
  • Transaction Management: - Transaction management service provides the ability to the user to execute more than one database statements at a time.
  • Object relational Mapping: - Object relational mapping is technique of mapping the data representation from an object model to a relational data model. This part of the Hibernate is used to select, insert, update and delete the records form the underlying table. When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query.
  • Hibernate is very good tool as far as object relational mapping , but in terms of connection management and transaction management, it is lacking in performance and capabilities. So usually hibernate is being used with other connection management and transaction management tools. For example apache DBCP is used for connection pooling with the Hibernate.
  • Hibernate provides a lot of flexibility in use. It is called "Lite" architecture when we only use the object relational mapping component. While in "Full Cream" architecture all the three component Object Relational mapping, Connection Management and Transaction Management) are used.

    Hibernate Example

    This section demonstrates how to create a simple program to insert record in Oracle database. You can run this program from Eclipse or from command prompt as well.

    Configuring Hibernate:-

    In this application Hibernate provided the connection pooling and transaction management is used for simplicity. Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment. Here is the code:

"-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@192.168.1.176:1521:CAM

wlnp

wlnp

10

true

org.hibernate.dialect.OracleDialect

update

In the above configuration file we specified to use the "CAM" which is running on “187.234.3.123” and the user of the database is “wlnp” with password “wlnp”. The dialect property is “org.hibernate.dialect.OracleDialect” which tells the Hibernate that we are using Oracle Database. Mapping resource specifies the table mapping to a POJO.

Hibernate, supports many database. With the use of the Hibernate (Object/Relational Mapping and Transparent Object Persistence for Java and SQL Databases), we can use the following databases dialect type property:

· DB2 - org.hibernate.dialect.DB2Dialect

· HypersonicSQL - org.hibernate.dialect.HSQLDialect

· Informix - org.hibernate.dialect.InformixDialect

· Ingres - org.hibernate.dialect.IngresDialect

· Interbase - org.hibernate.dialect.InterbaseDialect

· Pointbase - org.hibernate.dialect.PointbaseDialect

· PostgreSQL - org.hibernate.dialect.PostgreSQLDialect

· Mckoi SQL - org.hibernate.dialect.MckoiDialect

· Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect

· MySQL - org.hibernate.dialect.MySQLDialect

· Oracle (any version) - org.hibernate.dialect.OracleDialect

· Oracle 9 - org.hibernate.dialect.Oracle9Dialect

· Progress - org.hibernate.dialect.ProgressDialect

· FrontBase - org.hibernate.dialect.FrontbaseDialect

· SAP DB - org.hibernate.dialect.SAPDBDialect

· Sybase - org.hibernate.dialect.SybaseDialect

· Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect

The property is the mapping for our contact table.

Hibernate JDBC Properties used :-

hibernate.connection.driver_class :-jdbc driver class

hibernate.connection.url :- jdbc URL

hibernate.connection.username :- database user

hibernate.connection.password :- database user password

hibernate.connection.pool_size :- maximum number of pooled connections

Hibernate.dialect :-The classname of a Hibernate Dialect

hibernate.show_sql :-Write all SQL statements to console (True/false).

hibernate.hbm2ddl.auto :- Automatically export schema DDL to the database when the SessionFactory is created. With create drop, the database schema will be dropped when the SessionFactory is closed explicitly. e.g. update | create | create-drop

Writing First Persistence Class: - Hibernate, uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column. Here is the code for Book. java:

/**

* Java Class to map to the database Book table

*/

package avakaya.book;

public class Book

{

private String bookId;

private String strBookName;

/**

* @return Returns the strBookName.

*/

public String getStrBookName()

{

return strBookName;

}

/**

* @param strBookName The strBookName to set.

*/

public void setStrBookName(String strBookName)

{

this.strBookName = strBookName;

}

/**

* Method getBookId

* Description :

* @return

*/

public String getBookId()

{

return bookId;

}

/**

* Method setBookId

* Description :

* @param string

*/

public void setBookId(String string)

{

bookId = string;

}

}

Mapping the Contact Object to the Database Contact table :- The file contact.hbm.xml is used to map Contact Object to the Contact table in the database. Here is the code for book.hbm.xml:

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Setting Up Database :- Create a table Contact under the data base.

CREATE TABLE BOOK ( ID VARCHAR2(10 BYTE), NAME VARCHAR2(10 BYTE) ) LOGGING NOCACHE NOPARALLEL;

Developing Code to Test Hibernate example:-

package avakaya.book;

import org.hibernate.Session

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

/**

* Hibernate example to inset data into Book table

*/

public class BookAccess

{

public static void main(String[] args)

{

Session session = null;

try

{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory =

new Configuration().configure().buildSessionFactory();

session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

//Create new instance of Contact and set values in it by reading them from form object

System.out.println("Inserting Record");

Book book = new Book();

book.setBookId("12348");

book.setStrBookName("MyBook2");

session.save(book);

tx.commit();

System.out.println("Done");

}

catch (Exception e)

{

e.printStackTrace();

System.out.println(e.getMessage());

}

finally

{

if (session != null)

{

session.flush();

session.close();

}

}

}

}


Hibernate O/R mapping -A Look

Let us consider the following file to understand O/R Mapping




















Hibernate mapping documents are simple xml documents. Here are important elements of the mapping file:.

element
The first or root element of hibernate mapping document is element. Between the <hibernate-mapping> tag

· class element(s) are present.

· element
The element maps the class object with corresponding entity in the database. It also tells what table in the database has to access and what column in that table it should use. Within one element, several mappings are possible.

· element
The element in unique identifier to identify and object. In fact element map with the primary key of the table. In the example :

primary key maps to the ID field of the table CONTACT. The attributes of the id element are:

o name: The property name used by the persistent class.

o column: The column used to store the primary key value.

o type: The Java data type used.

o unsaved-value: This is the value used to determine if a class has been made persistent. If the value of the id attribute is null, then it means that this object has not been persisted.

· element
The method is used to generate the primary key for the new record. Here are some of the commonly used generators:

* Increment - This is used to generate primary keys of type long, short or int that are unique only. It should not be used in the clustered deployment environment.

* Sequence - Hibernate can also use the sequences to generate the primary key. It can be used with DB2, PostgreSQL, Oracle, SAP DB databases.

* Assigned - Assigned method is used when application code generates the primary key.

· element
The property elements define standard Java attributes and their mapping into database schema. The property element supports the column child
element to specify additional properties, such as the index name on a column or a specific column type.

1.1. Understanding Hibernate element

In this section we will look into the element and its options.Hibernate generator element generates the primary key for new record. There are many options provided by the generator method to be used in different situations.

The element

This is the optional element under element. The element is used to specify the class name to be used to generate the primary key for new record while saving a new record. The element is used to pass the parameter (s) to the class. Here is the example of generator element from our first application In this case element do not generate the primary key and it is required to set the primary key value before calling save() method.

Here is the lists of some commonly used generators in hibernate:

Generator

Description

increment

It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.

identity

It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

sequence

The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

hilo

The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection.

seqhilo

The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

uuid

The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.

guid

It uses a database-generated GUID string on MS SQL Server and MySQL.

native

It picks identity, sequence or hilo depending upon the capabilities of the underlying database.

assigned

lets the application to assign an identifier to the object before save() is called. This is the default strategy if no element is specified.

select

retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value.

foreign

uses the identifier of another associated object. Usually used in conjunction with a primary key association.

1.1. Using Hibernate to generate id incrementally

As we have seen in the last section that the increment class generates identifiers of type long, short or int that is unique only when no other process is inserting data into the same table. In this lesson I will show you how to write running program to demonstrate it. You should not use this method to generate the primary key in case of clustured environment.

In this section we will create/alter table in database, add mappings in the book.hbm.xml file, develop/modify the POJO class (Book.java), and write the program to test it out.

Create Table in the database:
User the following sql statement to create a new table in the database

CREATE TABLE BOOK ( ID INTEGER DEFAULT 0, BOOKNAME VARCHAR2(50 BYTE) DEFAULT NULL ) LOGGING NOCACHE NOPARALLEL;

Developing POJO Class (Book.java)
Book.java is our POJO class which is to be persisted to the database table "book”

/**

* Java Class to map to the database Book table

*/

package avakaya.book;

/**

* Class Book

* Description : POJO

* @version $Revision: 1.0 $

*/

public class Book {

private int lngBookId;

private String strBookName;

/**

* @return Returns the lngBookId.

*/

public int getLngBookId() {

return lngBookId;

}

/**

* @param lngBookId The lngBookId to set.

*/

public void setLngBookId(int lngBookId) {

this.lngBookId = lngBookId;

}

/**

* @return Returns the strBookName.

*/

public String getStrBookName() {

return strBookName;

}

/**

* @param strBookName The strBookName to set.

*/

public void setStrBookName(String strBookName) {

this.strBookName = strBookName;

}

}

Adding Mapping entries to existing.hbm.xml / book.hbm.xml
Add the following mapping code into the contact.hbm.xml file

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Note:- We have used !!!

Adding > to hibernate.cfg.xml

"-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@192.168.1.176:1521:CAM

wlnp

wlnp

10

true

org.hibernate.dialect.OracleDialect

update

Write the client program and test it out
Here is the code of our client program to test the application

/****************************************************************************

* @(#) IdIncrementExample.java Feb 22, 2006

****************************************************************************/

package avakaya.book;

//Hibernate Imports

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

/**

* Class

* Description :

* @version $Revision: 1.0 $

* @author Avakaya R

*

*/

public class IdIncrementExample

{

public static void main(String[] args)

{

Session session = null;

try

{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory =

new Configuration().configure().buildSessionFactory();

session = sessionFactory.openSession();

org.hibernate.Transaction tx = session.beginTransaction();

//Create new instance of Contact and set values in it by reading them from form object

System.out.println("Inserting Book object into database..");

Book book = new Book();

book.setStrBookName("Hibernate Tutorial2");

session.save(book);

System.out.println("Book object persisted to the database.");

tx.commit();

session.flush();

session.close();

}

catch (Exception e)

{

System.out.println(e.getMessage());

}

finally

{

}

}

}

Hibernate Querey Language

Hibernate Query Language or HQL for short is extremely powerful query language. HQL is much like SQL and are case-insensitive, except for the names of the Java Classes and properties. Hibernate Query Language is used to execute queries against database. Hibernate automatically generates the sql query and execute it against underlying database if HQL is used in the application. HQL is based on the relational object models and makes the SQL object oriented. Hibernate Query Language uses Classes and properties instead of tables and columns. Hibernate Query Language is extremely powerful and it supports Polymorphism, Associations, Much less verbose than SQL.

There are other options that can be used while using Hibernate. These are Query By Criteria (QBC) and Query BY Example (QBE) using Criteria API and the Native SQL queries. In this section we will understand HQL in detail.

Why to use HQL?

  • Full support for relational operations: HQL allows representing SQL queries in the form of objects. Hibernate Query Language uses Classes and properties instead of tables and columns.
  • Return result as Object: The HQL queries return the query result(s) in the form of object(s), which is easy to use. This elemenates the need of creating the object and populate the data from result set.
  • Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results the query results along with all the child objects if any.
  • Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the applications.
  • Support for Advance features: HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls.
  • Database independent: Queries written in HQL are database independent (If database supports the underlying feature).

Understanding HQL Syntax
Any Hibernate Query Language may consist of following elements:

  • Clauses
  • Aggregate functions
  • Subqueries

Clauses in the HQL are:

  • from
  • select
  • where
  • order by
  • group by

Aggregate functions are:

  • avg(...), sum(...), min(...), max(...)
  • count(*)
  • count(...), count(distinct ...), count(all...)

Subqueries
Subqueries are nothing but it’s a query within another query. Hibernate supports Subqueries if the underlying database supports it.

1.1. Preparing table for HQL Examples

Create an insurance table

CREATE TABLE Insurance (

ID INTEGER default 0,

insurance_name varchar(50) default NULL,

invested_amount INTEGER default NULL,

investement_date DATE default NULL,

PRIMARY KEY (ID)

)



1.1. Writing ORM for Insurance table

Create POJO class:
Here is the code of our java file (Insurance.java), which we will map to the insurance table

/****************************************************************************

* @(#) Insurance.java Feb 22, 2006

****************************************************************************/

package avakaya.insurance;

import java.util.Date;

/**

* Class

* Description : POJO Class

* @author Avakaya R

*

*/

public class Insurance

{

private int lngInsuranceId;

private String insuranceName;

private int investementAmount;

private Date investementDate;

/**

* Method getInsuranceName

* Description :

* @return

*/

public String getInsuranceName()

{

return insuranceName;

}

/**

* Method getInvestementAmount

* Description :

* @return

*/

public int getInvestementAmount()

{

return investementAmount;

}

/**

* Method getInvestementDate

* Description :

* @return

*/

public Date getInvestementDate()

{

return investementDate;

}

/**

* Method getLngInsuranceId

* Description :

* @return

*/

public int getLngInsuranceId()

{

return lngInsuranceId;

}

/**

* Method setInsuranceName

* Description :

* @param string

*/

public void setInsuranceName(String string)

{

insuranceName = string;

}

/**

* Method setInvestementAmount

* Description :

* @param i

*/

public void setInvestementAmount(int i)

{

investementAmount = i;

}

/**

* Method setInvestementDate

* Description :

* @param date

*/

public void setInvestementDate(Date date)

{

investementDate = date;

}

/**

* Method setLngInsuranceId

* Description :

* @param i

*/

public void setLngInsuranceId(int i)

{

lngInsuranceId = i;

}

}

Adding mappings into existing.hbm.xml file / insurance.hbm.xml

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Adding > to hibernate.cfg.xml

"-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@192.168.1.176:1521:CAM

wlnp

wlnp

10

true

org.hibernate.dialect.OracleDialect

update

1.1. HQL from clause Example

In this example you will learn how to use the HQL from clause. The from clause is the simplest possible Hibernate Query.

Syntax :-

From <> instance name

Example of from clause is:

from Insurance insurance

Here is the full code of the from clause example:

/****************************************************************************

* @(#) FromClauseHQLExample.java Feb 22, 2006

****************************************************************************/

package avakaya.insurance;

import java.util.Iterator;

import org.hibernate.Session;

import org.hibernate.*;

import org.hibernate.cfg.*;

public class FromClauseHQLExample

{

public static void main(String[] args)

{

Session session = null;

try

{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory =

new Configuration().configure().buildSessionFactory();

session = sessionFactory.openSession();

//Using from Clause

String SQL_QUERY = "from Insurance insurance"; // use from to get all records

Query query = session.createQuery(SQL_QUERY);

for (Iterator it = query.iterate(); it.hasNext();)

{

Insurance insurance = (Insurance)it.next();

System.out.println("ID: " + insurance.getLngInsuranceId());

System.out.println(

"First Name: " + insurance.getInsuranceName());

}

}

catch (Exception e)

{

System.out.println(e.getMessage());

}

finally

{

session.flush();

session.close();

}

}

}

1.1. Hibernate Select Clause

In this section we will write example code to select the data from Insurance table using Hibernate Select Clause. The select clause picks up objects and properties to return in the query result set.

Syntax

Select <> , <> ……. from <> obj

Here is the query example:

Select insurance.lngInsuranceId, insurance.insuranceName, insurance.investementAmount, insurance.investementDate from Insurance insurance

This selects all the rows (insurance.lngInsuranceId, insurance.insuranceName, insurance.investementAmount, insurance.investementDate) from Insurance table,

Hibernate generates the necessary sql query and selects all the records from Insurance table. Here is the code of our java file which shows how select HQL can be used:

/****************************************************************************

* @(#) SelectClauseExample.java Feb 22, 2006

****************************************************************************/

package avakaya.insurance;

import java.util.Iterator;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class SelectClauseExample

{

public static void main(String[] args)

{

Session session = null;

try

{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory =

new Configuration().configure().buildSessionFactory();

session = sessionFactory.openSession();

//Create Select Clause HQL

String SQL_QUERY =

"Select insurance.lngInsuranceId,insurance.insuranceName,"

+ "insurance.investementAmount,insurance.investementDate from Insurance insurance";

Query query = session.createQuery(SQL_QUERY);

for (Iterator it = query.iterate(); it.hasNext();)

{

Object[] row = (Object[])it.next();

System.out.println("ID: " + row[0]);

System.out.println("Name: " + row[1]);

System.out.println("Amount: " + row[2]);

}

session.close();

}

catch (Exception e)

{

System.out.println(e.getMessage());

}

finally

{

}

}

}

1.1. HQL Where Clause Example

Where Clause is used to limit the results returned from database. It can be used with aliases and if the aliases are not present in the Query, the properties can be referred by name. For example:

from Insurance where lngInsuranceId='1'

Where Clause can be used with or without Select Clause. Here the example code:

/****************************************************************************

* @(#) WhereClauseExample.java Feb 22, 2006

****************************************************************************/

package avakaya.insurance;

import java.util.Iterator;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class WhereClauseExample

{

public static void main(String[] args) {

Session session = null;

try{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

session =sessionFactory.openSession();

System.out.println("*******************************");

System.out.println("Query using Hibernate Query Language");

//Query using Hibernate Query Language

String SQL_QUERY =" from Insurance as insurance where insurance.lngInsuranceId='1'";

Query query = session.createQuery(SQL_QUERY);

for(Iterator it=query.iterate();it.hasNext();){

Insurance insurance=(Insurance)it.next();

System.out.println("ID: " + insurance.getLngInsuranceId());

System.out.println("Name: " + insurance.getInsuranceName());

}

System.out.println("*******************************");

System.out.println("Where Clause With Select Clause");

//Where Clause With Select Clause

SQL_QUERY ="Select insurance.lngInsuranceId,insurance.insuranceName," +

"insurance.investementAmount,insurance.investementDate from Insurance insurance "+

" where insurance.lngInsuranceId='1'";

query = session.createQuery(SQL_QUERY);

for(Iterator it=query.iterate();it.hasNext();){

Object[] row = (Object[]) it.next();

System.out.println("ID: " + row[0]);

System.out.println("Name: " + row[1]);

}

System.out.println("*******************************");

session.close();

}catch(Exception e){

System.out.println(e.getMessage());

}finally{

}

}

}

1.2. HQL Group By Clause Example

Group by clause is used to return the aggregate values by grouping on returned component. HQL supports Group By Clause. In our example we will calculate the sum of invested amount in each insurance type. Here is the java code for calculating the invested amount insurance wise

/****************************************************************************

* @(#) HQLGroupByExample.java Feb 22, 2006

****************************************************************************/

package avakaya.insurance;

import java.util.Iterator;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HQLGroupByExample

{

public static void main(String[] args)

{

Session session = null;

try

{

// This step will read hibernate.cfg.xml and prepare hibernate for

// use

SessionFactory sessionFactory =

new Configuration().configure().buildSessionFactory();

session = sessionFactory.openSession();

//Group By Clause Example

String SQL_QUERY =

"select sum(insurance.investementAmount),insurance.insuranceName "

+ "from Insurance insurance group by insurance.insuranceName";

Query query = session.createQuery(SQL_QUERY);

for (Iterator it = query.iterate(); it.hasNext();)

{

Object[] row = (Object[])it.next();

System.out.println("Invested Amount: " + row[0]);

System.out.println("Insurance Name: " + row[1]);

}

session.close();

}

catch (Exception e)

{

System.out.println(e.getMessage());

}

finally

{

}

}

}

1.1. HQL Order By Example

Order by clause is used to retrieve the data from database in the sorted order by any property of returned class or components. HQL supports Order By Clause. In our example we will retrieve the data sorted on the insurance type. Here is the java example code:

/****************************************************************************

* @(#) HQLOrderByExample.java Feb 22, 2006

****************************************************************************/

package avakaya.insurance;

import org.hibernate.Session;

import org.hibernate.*;

import org.hibernate.cfg.*;

import java.util.*;

public class HQLOrderByExample

{

public static void main(String[] args)

{

Session session = null;

try

{

// This step will read hibernate.cfg.xml and prepare hibernate for

// use

SessionFactory sessionFactory =

new Configuration().configure().buildSessionFactory();

session = sessionFactory.openSession();

//Order By Example

String SQL_QUERY =

" from Insurance as insurance order by insurance.insuranceName";

Query query = session.createQuery(SQL_QUERY);

for (Iterator it = query.iterate(); it.hasNext();)

{

Insurance insurance = (Insurance)it.next();

System.out.println("ID: " + insurance.getLngInsuranceId());

System.out.println("Name: " + insurance.getInsuranceName());

}

session.close();

}

catch (Exception e)

{

System.out.println(e.getMessage());

}

finally

{

}

}

}

1. Hibernate Criteria Query Example

The Criteria interface allows to create and execute object-oriented queries. Criteria Query is used mostly in case of multi criteria search screens, where HQL is not very effective.

The interface org.hibernate.Criteria is used to create the criterion for the search. The org.hibernate.Criteria interface represents a query against a persistent class. The Session is a factory for Criteria instances. Here is a simple example of Hibernate Criterial Query for the insurance table created earlier

/****************************************************************************

* @(#) HibernateCriteriaQueryExample.java Feb 22, 2006

****************************************************************************/

package avakaya.insurance;

import java.util.Iterator;

import org.hibernate.Criteria;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HibernateCriteriaQueryExample

{

public static void main(String[] args)

{

Session session = null;

try

{

// This step will read hibernate.cfg.xml and prepare hibernate for

// use

SessionFactory sessionFactory =

new Configuration().configure().buildSessionFactory();

session = sessionFactory.openSession();

//Criteria Query Example

Criteria crit = session.createCriteria(Insurance.class);

java.util.List insurances = crit.list();

for (Iterator it = insurances.iterator(); it.hasNext();)

{

Insurance insurance = (Insurance)it.next();

System.out.println("ID: " + insurance.getLngInsuranceId());

System.out.println("Name: " + insurance.getInsuranceName());

}

session.close();

}

catch (Exception e)

{

System.out.println(e.getMessage());

}

finally

{

}

}

}

The above Criteria Query example selects all the records from the table and displays on the console. In the above code the following code creates a new Criteria instance, for the class Insurance:

Criteria crit = session.createCriteria(Insurance.class);

The code:

List insurances = crit.list();

creates the sql query and execute against database to retrieve the data.

1.1. Criteria Query Examples

In the last lesson we learnt how to use Criteria Query to select all the records from Insurance table. In this lesson we will learn how to restrict the results returned from the database. Different method provided by Criteria interface can be used with the help of Restrictions to restrict the records fetched from database.

Criteria Interface provides the following methods:

Method

Description

add

The Add method adds a Criterion to constrain the results to be retrieved.

addOrder

Add an Order to the result set.

createAlias

Join an association, assigning an alias to the joined entity

createCriteria

This method is used to create a new Criteria, "rooted" at the associated entity.

setFetchSize

This method is used to set a fetch size for the underlying JDBC query.

setFirstResult

This method is used to set the first result to be retrieved.

setMaxResults

This method is used to set a limit upon the number of objects to be retrieved.

uniqueResult

This method is used to instruct the Hibernate to fetch and return the unique records from database.

Class Restriction provides built-in criterion via static factory methods. Important methods of the Restriction class are:

Method

Description

Restriction.allEq

This is used to apply an "equals" constraint to each property in the key set of a Map

Restriction.between

This is used to apply a "between" constraint to the named property

Restriction.eq

This is used to apply an "equal" constraint to the named property

Restriction.ge

This is used to apply a "greater than or equal" constraint to the named property

Restriction.gt

This is used to apply a "greater than" constraint to the named property

Restriction.idEq

This is used to apply an "equal" constraint to the identifier property

Restriction.ilike

This is case-insensitive "like", similar to Postgres ilike operator

Restriction.in

This is used to apply an "in" constraint to the named property

Restriction.isNotNull

This is used to apply an "is not null" constraint to the named property

Restriction.isNull

This is used to apply an "is null" constraint to the named property

Restriction.le

This is used to apply a "less than or equal" constraint to the named property

Restriction.like

This is used to apply a "like" constraint to the named property

Restriction.lt

This is used to apply a "less than" constraint to the named property

Restriction.ltProperty

This is used to apply a "less than" constraint to two properties

Restriction.ne

This is used to apply a "not equal" constraint to the named property

Restriction.neProperty

This is used to apply a "not equal" constraint to two properties

Restriction.not

This returns the negation of an expression

Restriction.or

This returns the disjuction of two expressions

Here is an example code that shows how to use Restrictions.like method and restrict the maximum rows returned by query by setting the Criteria.setMaxResults() value to 5.

/****************************************************************************

* @(#) HibernateCriteriaQueryExample2.java Feb 22, 2006

****************************************************************************/

package avakaya.insurance;

import org.hibernate.Session;

import org.hibernate.*;

import org.hibernate.criterion.*;

import org.hibernate.cfg.*;

import java.util.*;

public class HibernateCriteriaQueryExample2

{

public static void main(String[] args)

{

Session session = null;

try

{

// This step will read hibernate.cfg.xml and prepare hibernate for

// use

SessionFactory sessionFactory =

new Configuration().configure().buildSessionFactory();

session = sessionFactory.openSession();

//Criteria Query Example

Criteria crit = session.createCriteria(Insurance.class);

crit.add(Restrictions.like("insuranceName", "%Life%"));

//Like condition

crit.setMaxResults(5); //Restricts the max rows to 5

List insurances = crit.list();

for (Iterator it = insurances.iterator(); it.hasNext();)

{

Insurance insurance = (Insurance)it.next();

System.out.println("ID: " + insurance.getLngInsuranceId());

System.out.println("Name: " + insurance.getInsuranceName());

}

session.close();

}

catch (Exception e)

{

System.out.println(e.getMessage());

}

finally

{

}

}

}