Hibernate is an Object Relation Mapping tool that maps:
Java classes to database tables
Java objects to rows
Due to this mapping, the user does not have to deal directly with SQL data types.
Such a mapping allows the programmer to interact with objects which are more natural to work with.
Hibernate example:
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
.
.
.
Person p = new Person ();
person.setAge (25);
person.setName ("John");
// Obtain hibernate session from factory
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
// Write using hibernate
session.beginTransaction();
session.save(p);
session.getTransaction().commit();
// Read using hibernate
Query q = session.createQuery ("from Person p where p.age = 25"); // note HQL's use of object notation.
itr = q.iterate();
while (itr.hasNext())
System.out.println(itr.next());
Hibernate Mapping File
Hibernate needs a mapping file which maps each table to a class.
Example:
The following is a description of the commonly used tags and their attributes:
<id>
- Primary key specification.
name -
Specifies the name of the id in class.
column
- The name of the database column for the id.
<generator>
- It is used to generate a unique id every time an object is
persisted to the database. It also specifies how the id element
will be created by using the following built in generators:
increment
- Used most often, each time the generator needs a new id it
performs a select on the database to determine the current largest
id and increments it to the next value.
native
- Picks the best strategy depending on the configured database.
assigned
- Used if you need to assign the id yourself in your application.
Set the id by using the set<identifier> method of the Java
class. The application assumes responsibility on keeping the id
unique.
<property>
- This field is defined for each field in the Java class that needs
to be persisted.
name
- Specifies class field’s name. The first character must be lowercase.
column
- Specifies the name of the column in the database.
<set>
- The most common collection mapping used in Hibernate.
<key column>
- Specifies the foreign key column.
<many-to-many>
- Sub-element of set.
Note: The above method of specifying mapping files is slightly cumbersome.
Now-a-days, annotation based mechanism of specifying mappings is rapidly gathering popularity.
A working example with annotations will be covered in the later chapters.
Hibernate Configuration File
Hibernate also needs a configuration file in xml whose format is as follows: