Results 1 to 1 of 1
Thread: Hibernate Java
- 09-22-2007, 10:18 PM #1
Hibernate Java
Hibernate is a very powerful and high performance object/relational persistence framework. It is used to develop persistent classes following object-oriented idiom - including association, inheritance, polymorphism, composition, and collections.
Hibernate uses runtime reflection to determine the persistent properties of a class rather than utilizing bytecode processing or code generation. 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.
Hibernate – Motivation
- It's used as a main part in JBoss, one of the most popular Application-Servers (and the most popular Open Source AS)
- It's very common and widely used
- Lot of documentation
- Easy to use.
Hibernate – Brief Overview
This diagram shows Hibernate using the database and configuration data to provide persistence services
(and persistent objects) to the application.
Hibernate – Detailed Overview
The "full cream" architecture abstracts the application away from the underlying JDBC / JTA APIs and lets take Hibernate care of the details.
A Hibernate application consists of 4 parts:
- Hibernate Properties File
- Hibernate Mapping (XML) File
- Hibernate Java Library
- HQL (Hibernate Query Language)
and also
- Java Class Files
- Database Schema
Hibernate – Example
To understand the concept, lets take an example. Consider an office environment where each employee has some boss and there is one employee who has no boss (the real boss). In software terms, we will represent this with one class called employee. The class has one attribute called name of type String and the relationship is self relationship and its Many to one. That is, many employees can have one boss.
´
Java class for employee will be:
The above class ‘Employee’ is quiet simple. I declared private variables and their getters and setters. Obviously getters and setter are public. This to note is I created a variable called ‘boss’ of type Employee. It will hold the object pointing to the boss of an employee. We also have getter and setter for ‘boss’.Java Code:package java_hybernate; public class Employee { private Long id; private String name; private Employee boss; protected Employee() {} // Hibernate requires this public Employee(String name) { this.name = name; } public Long getId() { return id; } private void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Employee getBoss() { return boss; } public void setBoss(Employee boss) { this.boss = boss; } }
Now lets talk about the database for this very example. We will have a table with 3 fields. I will use MySQL for this example. Script to create the required table:
Hibernate – Mapping FileJava Code:# Database: hibernate_test # Table: 'employee' CREATE TABLE `employee` ( `ID` int(11) NOT NULL auto_increment, `NAME` varchar(80) default '', `BOSS_ID` int(11) default '0', PRIMARY KEY (`ID`) ) ENGINE=MyISAM;
Mapping file is required to map attributes of Java class to database fields. Following information is required for creating a mapping file.
- Class
- Id
- Properties
- Relationships
Hibernate – Mapping File (Class)
- name: Fully qualified name of the persistent class (or interface)
- table: Name of its database table
- discriminator-value: Used to distinguish objects when using a single table
Lets consider a simple example:Java Code:<class name="ClassName" table="tableName" discriminator-value="discriminator_value“ optimistic-lock="none|version|dirty|all" mutable="true|false" schema="owner" persister="PersisterClass"> </class>
Example:
Hibernate – Mapping File (Id)Java Code:<class name="hello.Employee” table="employee"> </class>
Hibernate’s classes mapped to database table must declare the primary key column of the DB table.
Java Code:<id name="propertyName" type="typename" column="column_name" unsaved-value="any|none|null|id_value"> <generator class="generatorClass"/> </id>
- name: Name of the Identifier property
- column: Name of the primary key column
- generator class: Method how the OIDs are generated. Possible values: native (recommended), identity, sequence, hilo, uuid, …
Lets consider a simple example:
Example:
Hibernate – Mapping File (Property)Java Code:<id name="id” column="ID"> <generator class=“native"/> </id>
Hibernate’s mapping file uses <property> element to declare a persistent, JavaBean style property of the class.
Java Code:<property name="propertyName" column="column_name" type="typename" update="true|false" insert="true|false" />
- name: Name of the Property
- column: Name of the mapped database column
Lets consider a simple example:
Example:
Hibernate– Mapping File (Relationships)Java Code:<property name="name” column="NAME"/>
A many-to-one reference in Hibernate’s mapping file is analogous to a simple Java reference. It is the same as the one-to-one situation except there is no requirement to have a shared Primary Key. Instead a Foreign Key is used.
Following variants can be used:Java Code:<class name="Foo" table="foo"> ... <many-to-one name="bar" column="bar_id"/> </class>
one-to-one, many-to-one, composite-id, set, one-to-many, many-to-many, map, components, subclass, joined-subclass
Lets consider a simple example:
Examples:
One to many relationship example:Java Code:<many-to-one name="boss” column="BOSS_ID"/>
Table structure:
Java Code:CUSTOMER: ID PROJECT: ID, CUSTOMER_ID
One to many relationship example:Java Code:<set name="projects" inverse="true" cascade="delete"> <key column="CUSTOMER_ID"/> <one-to-many class="Project"/> </set>
Table structure:
Java Code:EMPLOYEE: ID EMPLOYEE_PROJECT: EMPLOYEE_ID, PROJECT_ID PROJECT: ID
Hibernate - Mapping of the class hello.EmployeeJava Code:<set name="project_participation" table="EMPLOYEE_PROJECT"> <key column="EMPLOYEE_ID"/> <many-to-many class="Project" column="PROJECT_ID"/> </set>
Save this in a file named Employee.hbm.xml and put it in the directory where your class hello.Employee resides.
Hibernate – Initialize runtime environmentJava Code:<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="hello.Employee" table="employee"> <id name="id" column="ID"> <generator class="native"/> </id> <property name="name" column="NAME"/> <many-to-one name="boss" column="BOSS_ID"/> </class> </hibernate-mapping>
Following code initializes the Hibernate’s runtime environemnt. You have to use it before start persisting data using hibernate
Hibernate – Example (Create and Save an Employee)Java Code:// Import Statements import org.hibernate.*; import org.hibernate.cfg.*; ... // And then inside your class // Looks for mapping files in same classpath location as class Configuration cfg = new Configuration() .addClass(hello.Employee.class); // This binds you to a database configuration SessionFactory _sessions = cfg.buildSessionFactory();
Consider that you have to create and save an employee in the database using Hibernate. We are continuing the same employee/boss example as given above. First initialize hibernate runtime environment as told before and then use following code:
Hibernate Java framework will generate the required SQL.Java Code:// Open a Session and a Transaction Session session = _sessions.openSession(); Transaction trans = session.beginTransaction(); Employee emp = new Employee("Dave Morris"); session.save(emp); // Flush all trans.commit(); session.close();
Hibernate – Example (Retrieving all Employees)Java Code:insert into employee (NAME, BOSS_ID) values (?, ?)
Considering the same example, now we want to retrieve all the employees. We will print the number of employees, along with their names. Iterator is used to go through each employee.
Hibernate Java framework will generate the required SQL.Java Code:import java.util.List; import java.util.Iterator; ... List employees = session.createQuery( "from Employee emp order by emp.name asc").list(); System.out.println(employees.size() + " employee(s) found:"); for(Iterator iter=employees.iterator(); iter.hasNext(); ) { Employee e2 = (Employee)iter.next(); System.out.println(e2.getName()); } ...
Hibernate – Example (Modifying an Employee)Java Code:select employee0_.ID as ID0_, employee0_.NAME as NAME0_, employee0_.BOSS_ID as BOSS3_0_ from employee employee0_ order by employee0_.NAME asc
Considering the same example, now we want to modify an employee using Hibernate. Its also easy. We have to provide the primary key of employee whose name is to be changed.
Hibernate Java framework will generate the required SQL. Just note that we simply entered few values and hibernate generated SQL script.Java Code:... Employee emp = (Employee)session.load(Employee.class, Long.valueOf("1")); emp.setName("Imran Khan"); // Commit Transaction ...
Hibernate – Example (Deleting an Employee)Java Code:select employee0_.ID as ID0_0_, employee0_.NAME as NAME0_0_, employee0_.BOSS_ID as BOSS3_0_0_ from employee employee0_ where employee0_.ID=? update employee set NAME=?, BOSS_ID=? where ID=?
Considering the same example, now we want to delete an employee using Hibernate. We have to provide the primary key of employee whose name is to be changed (as we did while modifying an employee.
Hibernate Java framework will generate the required SQL.Java Code:... Employee emp = (Employee)session. load(Employee.class, Long.valueOf("1")); session.delete(emp); // Commit Transaction ...
Hibernate – How to run itJava Code:select employee0_.ID as ID0_0_, employee0_.NAME as NAME0_0_, employee0_.BOSS_ID as BOSS3_0_0_ from employee employee0_ where employee0_.ID=? delete from employee where ID=?
Running an application developed using Hibernate can be tricky for newbies. Just remember the following settings and you won’t get lost.
Set the environment variables and include all necessary libraries into the Classpath. Because there are so many libraries, the best way is to include all JAR-files from $HIBERNATE_HOME and $HIBERNATE_HOME/lib.
Hibernate – Logging
Logging is very important these days. Suppose you developed an application and it passed all the tests and was delivered to the client. Now, after few weeks he reported that the application crashed while working. How you will know what caused that crash? You have to spend many hours even days trying to figure that caused that failure. If you had enabled logging, you could simple read log files and track the problem area.
Hibernate uses Log4J for logging.
Log4j is an OpenSource logging API developed under the Jakarta Apache project. Log4j is widely used for logigng purpose because it is fully configurable, robust, reliable, easily extendible, and easy to implement framework. It helps debugging and monitoring Java applications. Lot of online material is available which can help newbies in getting familiar with this.
To enable this, create a file called log4j.properties and put it in the same directory like the hibernate.properties.
Example:
log4j.properties
Hibernate ToolsJava Code:# Direct log messages to stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # Root logger option log4j.rootLogger=INFO, stdout # Hibernate logging options log4j.logger.org.hibernate=INFO # Log JDBC bind parameter runtime arguments log4j.logger.org.hibernate.type=INFO
You can use following tools for Hibernate:
- Eclipse Integration (i.e. XML-support)
- DDL schema generation from a mapping file (hbm2ddl)
- Java source generation from a mapping file (hbm2java)
Middlegen (mapping file generation from an existing database schema) is a third party tool that can be used for Hibernate.
Similar Threads
-
Hibernate order by query thru java solution urgently reqd
By altaf in forum JDBCReplies: 0Last Post: 03-12-2008, 02:23 PM -
Java Hibernate
By CASIDOLOUIS in forum Advanced JavaReplies: 0Last Post: 02-11-2008, 01:17 AM -
Lead Java developer -- Spring and Hibernate experience
By orjueladiego in forum Jobs OfferedReplies: 0Last Post: 10-29-2007, 01:50 PM -
Hibernate Java Persistence
By JavaBean in forum Java TutorialReplies: 0Last Post: 09-22-2007, 10:02 PM -
org.hibernate.ejb.Version <clinit> INFO: Hibernate EntityManager 3.2.0.CR1
By Heather in forum JDBCReplies: 2Last Post: 06-30-2007, 03:01 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks