Hibernate Environment Setup and session api methods:
Downloading Hibernate:
Following are the simple steps to download and install Hibernate on your machine.
- Make a choice whether you want to install Hibernate on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix.
- Download the latest version of Hibernate from http://www.hibernate.org/downloads. or you can download from http://sourceforge.net/projects/hibernate/files/hibernate3/ and unpack the archive after download.
- Create a new Java Project and enter project name.
- Create lib and src subdirectories in this project. (When you create a new Java Project in Eclipse IDE, src subdirectory will be created automatically.)
- Copy JAR files which are listed below, from hibernate distribution that you have downloaded to the lib directory of your project.
Under lib/required directory of the hibernate distrubution:
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
slf4j-api-1.6.1.jar
Under lib/jpa directory of the hibernate distrubution:
hibernate-jpa-2.0-api-1.0.1.Final.jar
Download slf4j-1.6.1.zip file from http://www.slf4j.org/download.html, unpack the archive and copy the slf4j-simple-1.6.1.jar file to lib directory.
slf4j-simple-1.6.1.jar
Additionally, you will need the database driver JAR that Hibernate uses to connect to your database. I use Oracle Express Edition(Oracle XE) and it’s database driver jar is here on Windows:
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar
Copy this ojdbc14.jar to the lib directory of the your project.
Note: You should replace this database driver JAR with a different database driver JAR if you have another database management system already installed.You only need to obtain a JDBC driver for it. For example, you must download MySQL Connector/J (official JDBC driver for MySQL) from http://www.mysql.com/downloads/connector/j/ if your database is MySQL and copy the database driver jar to the HibernateApplication\lib directory.
After these steps project will look like this:
Now I will create a User library on Eclipse IDE. Then, I will add all JAR files in the project\lib directory to this User library and add this User library to the project build path.
Click Window–>Preferences on the top menu bar of Eclipse.
Click Java–>Build Path–>User Libraries and click New button then enter “Hibernate” as the User library name.
Select “Hibernate” User library that we just created and click Add JARS… button.
Select all JAR files in the lib folder of the project and click Open button to add all JAR files to “Hibernate” User library.
Now “Hibernate” User library is ready and we can add this User library to project build path.
Right click to project and click Build Path–>Add Libraries Then, select “User Library” and click Next button.
Finally, select “Hibernate” User library and click Finish button.
you have installed Hibernate on Eclipse IDE.
Hibernate Configuration
Hibernate requires to know in advance where to find the mapping information that defines how your Java classes relate to the database tables. Hibernate also requires a set of configuration settings related to database and other related parameters. All such information is usually supplied as a standard Java properties file called hibernate.properties, or as an XML file named hibernate.cfg.xml.
I will consider XML formatted file hibernate.cfg.xml to specify required Hibernate properties in my examples. Most of the properties take their default values and it is not required to specify them in the property file unless it is really required. This file is kept in the root directory of your application’s classpath.
Hibernate requires to know in advance where to find the mapping information that defines how your Java classes relate to the database tables. Hibernate also requires a set of configuration settings related to database and other related parameters. All such information is usually supplied as a standard Java properties file called hibernate.properties, or as an XML file named hibernate.cfg.xml.
I will consider XML formatted file hibernate.cfg.xml to specify required Hibernate properties in my examples. Most of the properties take their default values and it is not required to specify them in the property file unless it is really required. This file is kept in the root directory of your application’s classpath.
What are different environment to configure hibernate:
There are mainly two types of environments in which the configuration of hibernate application differs.
i. Managed environment – In this kind of environment everything from database connections, transaction boundaries, security levels and all are defined. An example of this kind of environment is environment provided by application servers such as JBoss, Weblogic,WebSphere.
ii. Non-managed environment – This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment.
Three different types of objects are categorized in Hibernate technology based on the state of the object. They are:
# Persistent Object
# Transient Object
# Detached Object
Persistent Object:
A persistent object is one which is associated with the current Session and has its state values synchronized with the database.
Transient Object:
A transient object doesn’t have any association with the current Session, but can be made persistent at a later time.
Detached Object:
A detached object was having an association at a previous point of time with the Session interface, but now is made to detach (taken-off) from the current Session.
Hibernate object state diagram representation :
Hibernate session api methods:
save() – save method stores an object into the database. That means it insert an entry if the identifier doesn’t exist, else it will throw error. If the primary key already present in the table, it cannot be inserted .save() returns seralizable object.
update() – update method in the hibernate is used for updating the object using identifier. If the identifier is missing or doesn’t exist, it will throw exception.
saveOrUpdate() – This method calls save() or update() based on the operation. If the identifier exists, it will call update method else the save method will be called.
Merge()- The merge() method checks the ID of the object we are sending as a parameter; if an object with that ID already existed in the session, that session object is replaced by the parameter object. If no such ID existed, the parameter object is added to the session.
Evict()- evict() will remove the perticular object from session and object will become
detached object.
Persist()- persist will work as save() method but it does not return any object identifier.
clear()-clear() will remove all the objects from session .then object will become either transient or detatched states.
eg.
Student s = new Student();
session.save(s);
session.clear(); // s will become transient
Student s=(student)session.load()
session.clear() // s will become detached
Use of ThreadLocal class
To ensure safe sessionfactory and session object instantiation and use.so we use two rules to be followed- static attribute and thread local construct.
Private static final SessionFactory sessionFactory;
Static {try {sessionFactory = new Configuration().
configure().buildSessionFactory();
} catch (HibernateException e) {
throw new RuntimeException(“SessionFactory Error – ” + e.getMessage(), e);
}}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
if (s == null) {
s = sessionFactory.openSession();
session.set(s);
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
if (s == null) {
s = sessionFactory.openSession();
session.set(s);
}
Difference between load() and get()
Load() –
-Only use the load() method if you are sure that the object exists.
-load() method will throw an exception if the unique id is not found in the database.
-load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.
Get()
-If you are not sure that the object exists, then use one of the get() methods.
-get() will hit the database immediately.
-get() method will return null if the unique id is not found in the database.
Difference between List() and Iterate()
List()-hits the database many times for a simple query.
-it is eager fetching.
iterate()-hits the database once and cache the result in session or second level cache.
Give better performance.
-it is lazy fetching
Difference between lazy fetching and eager fetching
-Lazy fetching decides whether to load child objects while loading the Parent Object. You need to do this setting respective hibernate mapping file of the parent class.
Lazy = true (means not to load child)
-By default the lazy loading of the child objects is true.
This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object
Eager fetching- when we do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.
eg. <set name=”address” inverse=”true” cascade=”delete” lazy=”false”>
Eager fetching- when we do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.
eg. <set name=”address” inverse=”true” cascade=”delete” lazy=”false”>
<key column=”a_id” />
<one-to-many class=”beans Address”/>
</set>
When lazy =false ,you load employee object that time child object address also loaded.
Calling method employee.getAddress() loaded data returns no database hit.
When lazy=true,you load employee object that time child object address not loaded. You need to hit one database hit for calling employee.getAddress()
Generator classes in hibernate framework:
<generator> element The optional <generator> child element names a Java class used to generate unique identifiers for instances of the persistent class.
<generator> element The optional <generator> child element names a Java class used to generate unique identifiers for instances of the persistent class.
<id><generator class=”native”> </generator></id>
increment- generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table.
identity-supports identity columns in DB2, MySQL, MS SQL Server, Sybase . The returned
identifier is of type long, short or int.
identifier is of type long, short or int.
sequence-
uses a sequence in Oracle. The returned identifier is of type long, short or int hilo-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.
seqhilo-uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int,given a named database sequence.
assigned-lets the application to assign an identifier to the object before save() is called.This is the default strategy if no <generator> 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
<one-to-one> primary key association.
<one-to-one> primary key association.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.