Você está na página 1de 6

Hibernate

Hibernate is a powerful, ultra-high performance object/relational persistence and query service for Java.
Hibernate gives you the option to code and work with Java and use Hibernate's capabilities to interact with
the database. No need to write SQL in your Java code. You work with Java objects and Hibernate does the
rest

We need a means of taking information from a SQL database and turn it into Java objects, and vice-versa.
The general problem is known as Object/Relational Mapping. Hibernate is a lightweight O/R mapping service
for Java and gives you the means for persisting your Java objects to and from an underlying database. Rather
than you writing the SQL and converting queries to and from first class objects, Hibernate can take care of all
this for you. You only concern yourself with the objects, Hibernate worries about the SQL and making sure
things end up in the right tables.

Quick Installation and Setup


 Install J2SDK 1.4.2
 Install Ant
 Go to http://www.hibernate.org/ and download Hibernate
 Install Hibernate by unzipping the file hibernate-2.1.6.zip to drive say F:
 Setup a Project Hierarchy by doing the following Create folder F:hlogin and then create sub-folders
F:hloginsrc and F:hloginlib
 Copy all the contents of F:hibernate-2.1lib to F:hloginlib
 Copy hibernate2.jar to F:hloginlib
 The example classes we are going to create are all going to reside in the folder
F:hloginsrccomtalimdemo. Create these sub-folders.

Quick Compile
 To quickly compile your Java code:
 At the folder F:hlogin type ant
 To run your Hibernate programs
 At the folder F:hlogin type ant run
 Build.xml
<project name="hlogin" default="compile" basedir=".">
<!-- change this to suit your environment -->
<!-- j2sdk 1.4.2 setup -->
<property name="jdk.home" value="F:/j2sdk1.4.2"/>
<!-- jdbc mysql driver location -->
<property name="driver.dir" value="F:/mysql-connector-java-3.0.12-production"/>
<!-- project structure - should not have to modify -->
<property name="lib.dir" value="lib"/>
<property name="src.dir" value="src"/>
<property name="class.dir" value="src"/>
<!-- CLASSPATH used during compilation -->
<path id="build.classpath">
<!-- Include our own classes, of course -->
<pathelement location="${class.dir}"/>
<!-- Include jars in the project library directory -->
<fileset dir="${lib.dir}">
<include name="*.jar"/>
</fileset>
<fileset dir="${driver.dir}">
<include name="*.jar"/>
</fileset>
</path>
<!-- Compiling rule -->
<target name="compile">
<javac destdir="${class.dir}" deprecation="on">
<classpath refid="build.classpath"/>
<src path="${src.dir}"/>
</javac>
</target>
<target name="run" description="Runs the Hibernate program">
<java classname="com.talim.demo.MyUsersTest" fork="yes">
<classpath refid="build.classpath"/>
</java>
</target>
</project>

The Development Process


There are several ways to approach Hibernate development. Here's the one that is probably the most
straightforward to understand:
 Create your SQL table to hold your persistent objects
 Create a Java bean that will represent that object in code
 Create a mapping file that Hibernate knows which bean properties map to which SQL fields
 Create a properties file so Hibernate knows your JDBC settings to get to the database
 Start using the Hibernate API
As you get more proficient, there are tools to help auto-generate either Beans from SQL or SQL from Beans
(and even plug-ins to make the mapping file for you), but let's do it the long way first, so you don't get
distracted.

Step 1: Create the table


The example we're working through is a very simple one. Lets say you need a users table (in say database
jboss).
CREATE TABLE myusers (
LogonID varchar(20) NOT NULL default '0',
Name varchar(40) default NULL,
Password varchar(20) default NULL,
EmailAddress varchar(40) default NULL,
LastLogon datetime default NULL,
PRIMARY KEY (LogonID)
);
We are using mySql, but you can use any database that you have a JDBC driver for. We've got a User table
with a Logon ID, Full Name, Password, Email and date of last logon. Next step is to write a Java bean to
handle a given User

Step 2: Write the Bean


Hibernate works via reflection on get/set methods of the objects, so we'll need to create the objects (as
beans) we want to persist.

package com.talim.demo;
import java.util.Date;
import java.io.Serializable;
public class MyUsers implements Serializable
{
private String userID;
private String userName;
private String password;
private String emailAddress;
private Date lastLogon;
public MyUsers()
{
}
public String getID()
{
return userID;
}
public void setID(String userID)
{
this.userID = userID;
}
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getEmailAddress()
{
return emailAddress;
}
public void setEmailAddress(String emailAddress)
{
this.emailAddress = emailAddress;
}
public Date getLastLogon()
{
return lastLogon;
}
public void setLastLogon(Date lastLogon)
{
this.lastLogon = lastLogon;
}
}

Step 3: Writing the Mapping File


So we've now got our SQL table, and the Java object that's going to map to it. We still need a way to tell
Hibernate how to map from one to the other. This is accomplished via a mapping file. Hibernate uses an XMl
document to track the mapping between Java classes and relational database tables.
The cleanest (most maintainable) way is to write one mapping file per object, and if you name it
YourObject.hbm.xml and put it in the same directory (F:hloginsrccomtalimdemo)as your real object,
Hibernate will make things even easier for you. Here's an example of what MyUsers.hbm.xml might look like:
<hibernate-mapping>
<class name="com.talim.demo.MyUsers" table="myusers">
<id name="ID" column="LogonId" type="string">
<generator class="assigned"/>
</id>
<property name="userName" column="Name" type="string"/>
<property name="password" type="string"/>
<property name="emailAddress" type="string"/>
<property name="lastLogon" type="date"/>
</class>
</hibernate-mapping>
Let's have a look at some lines of interest in our file. The first tag of interest is the class tag. Here we map
from the class name to the users table in our database. Let's skip the ID tag for a moment and talk about the
property tags. A cursory scan will show this is where the work is being done. The name attribute is the
property on our Java bean, and the column is the name of the field in our database. The type attribute is
optional (Hibernate will use reflection for a best-guess if you leave it out) - but I've put it in here for
completeness.

Ok. Let's return to that ID tag. You may have guessed that this tag has something to do with mapping to the
primary key of the table. You'd be right. The form of the ID tag is very similar to the property tags we just
looked at. We map from the bean property (name) to the target database field (column).

The embedded generator tag tells Hibernate how it should produce the primary key (it's quite happy to
generate one for you, of whatever type you prefer, but you'll need to tell it how). In our case, we set it to
assigned, meaning that our bean is going to generate its own keys (the User object will always need to have a
UserID after all).

Step 4: Creating a Properties File for Your Database


We still haven't told Hibernate where to find our database. The most straightforward way is to feed Hibernate
a properties object, with settings for the connection strings, passwords, etc. If you name this file
hibernate.properties, copy it to folder
F:hloginsrc and put it in your classpath, Hibernate will pick it up automatically. Here's what it looks like:

hibernate.dialect=net.sf.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://127.0.0.1:3306/jboss
hibernate.connection.username=
hibernate.connection.password=

The example above uses a mysql driver, connects to the jboss database on 127.0.0.1, and uses the supplied
username and password. There are a bunch of other properties you can set to "tune" how Hibernate accesses
your database of choice. Once again, checkout the document for detailed information.
An alternative approach is to specify a full configuration in a file named hibernate.cfg.xml. This file can be
used as a replacement for the hibernate.properties file or, if both are present, override properties. The XML
configuration file is by default expected to be in the root of your CLASSPATH.

Step 5: Start using the Hibernate API


If all has gone well so far, you'll have the following:
 A SQL User table in your database
 MyUsers.java - your Java bean object to persist
 MyUsers.hbm.xml - your Hibernate mapping file
 hibernate.properties - your properties file with JDBC connection info
Making use of Hibernate in your source is pretty straightforward.
 Create a Configuration object
 Tell the Configuration about the type of objects you want to map
 Create a Session to your database of choice
 Load, Save and Query your objects
 flush() your Session back to the database

Steps 1 and 2
The Configuration object is based on the properties file, we have put in the standard place

Configuration config = new Configuration();


Config.addClass(MyUsers.class);

This assumes you've got a MyUsers.hbm.xml file in the same directory as your user class. If you decided to
call your file something else, use ds.storeFile("MyMappingFile.hbm.xml").
Step 3
The Session object represents a connection to your backend database. You can feed Hibernate a JDBC session
that you've created by hand, but I'm lazy, so I'm just going to feed Hibernate the properties file with my
settings, and let it do the work for me.
// Then build a session to the database
SessionFactory sf = config.buildSessionFactory(); // or supply a Properties arg
Session session = sf.openSession();
I've called my properties file hibernate.properties and put it in my classpath, but if you've called yours
something different (or you want to create the Properties in code), then you'll need to feed your own
Properties object to buildSessionFactory().

Step 4
Now you just use your objects in a Java-native way. Would you like to store a new User in the database? Try
something like this:
// Create new User and store them the database
MyUsers newUser = new MyUsers();
newUser.setID("satish_talim");
newUser.setUserName("Satish Talim");
newUser.setPassword("informex");
newUser.setEmailAddress( satish.talim@gmail.com This email address is being protected from
spam bots, you need Javascript enabled to view it );
newUser.setLastLogon(new Date());
// And the Hibernate call which stores it
session.save(newUser);
As you can see, the great thing about Hibernate is the low overhead. For the most part you just worry about
your business objects, and make a single call to Hibernate when you're done.
Step 5
Every so often your Hibernate Session object will flush itself to the database to make the database is in sync
with your memory copies of objects. You'll want to free up the JDBC connection that Hibernate's using, so
you'll typically shut down with:
// close our session and release resources
session.flush();
session.close();
// NB: some non-MySQL (Sybase, etc) database users also need to...
// session.connection().commit();
(Depending on your JDBC driver, you'll need to commit the underlying connection too. You don't need this if
you're using mySQL, but on other transactional databases (like Sybase), you need an extra statement after
the close calling session.connection().commit()).

Example
Here’s the code for inserting a record in our table MyUsers

package com.talim.demo;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import com.talim.demo.MyUsers;
import java.util.Date;
public class MyUsersTest
{
public static void main(String[] args) throws Exception
{
// Create a configuration based on the properties file we
// have put in the standard place
Configuration config = new Configuration();
// Tell it about the classes we want mapped, taking advantage
// of the way we have named their mapping documents
config.addClass(MyUsers.class);
// A SessionFactory is Hibernate's concept of a single datastore
// Get the sesion factory we can use for persistence
SessionFactory sessionFactory = config.buildSessionFactory();
// Hibernate's Session, is the persistence manager interface,
// we use it to store and retrieve MyUsers to and from the database
// Ask for a session using the JDBC information we have configured
Session session = sessionFactory.openSession();
// Store a new User in the database
try
{
MyUsers newUser = new MyUsers();
newUser.setID("satish_talim");
newUser.setUserName("Satish Talim");
newUser.setPassword("informex");
newUser.setEmailAddress(" satish.talim@gmail.com This email address is being protected from
spam bots, you need Javascript enabled to view it ");
newUser.setLastLogon(new Date());
// And the Hibernate call which stores it
session.save(newUser);
}
finally
{
// close our session and release resources
session.flush();
session.close();
}
// Clean up after ourselves
sessionFactory.close();
}
}

Você também pode gostar