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.
Person p = new Person ();
// Obtain hibernate session from factory
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
// Write using hibernate
// Read using hibernate
Query q = session.createQuery ("from Person p where p.age = 25"); // note HQL's use of object notation.
itr = q.iterate();
Hibernate Mapping File
Hibernate needs a mapping file which maps each table to a class.
The following is a description of the commonly used tags and their attributes:
- Primary key specification.
Specifies the name of the id in class.
- The name of the database column for the id.
- 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:
- 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.
- Picks the best strategy depending on the configured database.
- 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
- This field is defined for each field in the Java class that needs
to be persisted.
- Specifies class field’s name. The first character must be lowercase.
- Specifies the name of the column in the database.
- The most common collection mapping used in Hibernate.
- Specifies the foreign key column.
- 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: