Escolar Documentos
Profissional Documentos
Cultura Documentos
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 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>
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;
}
}
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).
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.
Steps 1 and 2
The Configuration object is based on the properties file, we have put in the standard place
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();
}
}