Hibernate
It is a popular open source object relational mapping tool for java platform.It provides powerful,ultra-high performance object/relational persistence and query service for java.
Object relational mapping(O/R mapping )
we mean the one-one mapping of class attributes with the columns of a database entity. Hibernate Hibernate maps java classes to the database tables.It also provides the data query and retrieval facilities that significantly reduce the development time. Hibernate allows transparent persistence that enables the applications to switch any database.Hibernate can be used in java swing apllications,java servlet based applications or j2ee apllications using EJB session beans.
Sample Hibernate code using Mysql database This is the code for the java pojo classes ie getter and setter methods for the fields
What is Session Factory see with an example.
package s2s.gateway.example;
public class simpleobj {
private Integer id;
private String name;
private String taste;
public simpleobj(){
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTaste() {
return taste;
}
public void setTaste(String taste) {
this.taste = taste;
}
public String toString() {
return “simpleobj: “+getId()<br>+” Name: “+getName()+” Taste: “+getTaste();
}
}
</pre>
<strong>Hibernate configuration(hibernate.cfg)
Here i use mysql as a database driver if you use oracle
or any database just change the dialect and connection properties like
username and password,diver name</strong>
<?xml version=’1.0′ encoding=’UTF-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD 3.0//EN”
“<a href=”http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd</a>”>
<hibernate-configuration>
<session-factory>
<property name=”connection.url”>jdbc:mysql://localhost:3306/car</property>
<property name=”connection.username”>root</property>
<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”connection.password”>root</property>
<property name=”transaction.factory_class”>org.hibernate.transaction.JDBCTransactionFactory</property>
<!– thread is the short name for
org.hibernate.context.ThreadLocalSessionContext
and let Hibernate bind the session automatically to the thread
–>
<property name=”current_session_context_class”>thread</property>
<!– this will show us all sql statements –>
<property name=”hibernate.show_sql”>true</property>
<!– mapping files –>
<mapping resource=”s2s/gateway/example/simpleobj.hbm.xml” />
</session-factory>
</hibernate-configuration>
<br>
simpleobj.hbm<br>
<pre>
<hibernate-mapping>
<class name=”s2s.gateway.example.simpleobj” table=”simpleobj”>
<id name=”id” column=”id” >
<generator/>
</id>
<property name=”name” column=”name” />
<property name=”taste” column=”taste” />
</class>
</hibernate-mapping>
<br>
<pre>
import s2s.gateway.example.simpleobj;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import s2s.gateway.hibernate.HibernateSessionFactory;
import s2s.gateway.hibernate.SessionFactoryUtil;
public class TestClient {
/**
* @param args
*/
public static void main(String[] args) {
simpleobj simple = new simpleobj();
simple.setName(“simpleforest”);
simple.setTaste(“original”);
createsimple(simple);
listsimpleobj();
simple.setName(“north”);
updatesimpleobj(simple);
//deletesimpleobj(countrysimpleobj); if you access this your table will be deleted
}
private static void listsimpleobj() {
Transaction tx = null;
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
List simpleobjs = session.createQuery(“select h from simpleobj as h”).list();
for (Iterator iter = simpleobjs.iterator(); iter.hasNext();) {
simpleobj element = (simpleobj) iter.next();
System.out.println(“Names of users:”+element.getName());
}
tx.commit();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
try {
// Second try catch as the rollback could fail as well
tx.rollback();
} catch (HibernateException e1) {
}
// throw again the first exception
throw e;
}
}
}
private static void deletesimpleobj(simpleobj simpleobj) {
Transaction tx = null;
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
session.delete(simpleobj);
tx.commit();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
try {
// Second try catch as the rollback could fail as well
tx.rollback();
} catch (HibernateException e1) {
}
// throw again the first exception
throw e;
}
}
}
private static voidcreatesimple(simpleobj simpleobj) {
Transaction tx = null;
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
session.save(simpleobj);
tx.commit();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
try {
// Second try catch as the rollback could fail as well
tx.rollback();
}
catch (HibernateException e1){}
}
else
{}
}
// throw again the first exception
}
private static void updatesimpleobj(simpleobj simpleobj) {
Transaction tx = null;
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
session.update(simpleobj);
tx.commit();
} catch (RuntimeException e) {
if (tx != null && tx.isActive()) {
try {
// Second try catch as the rollback could fail as well
tx.rollback();
} catch (HibernateException e1) {
}
// throw again the first exception
throw e;
}
}
}
}
Configures and provides access to Hibernate
sessions, tied to the current thread of execution.
Follows the Thread Local Session pattern, see
href="http://hibernate.org/42.html">For more
Hibernate Help
Location of hibernate.cfg.xml file.
Location should be on the classpath as Hibernate
uses #resourceAsStream style lookup for its
configuration file.
The default classpath location of the hibernate
config file is in the default package. Use
#setConfigFile() to update the location of the
configuration file for the current session.
Example:
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static String CONFIG_FILE_LOCATION =
"/hiberEX1Package/hibernate.cfg.xml";
private static final ThreadLocal
threadLocal = new ThreadLocal();
private static Configuration configuration = new
Configuration();
private static org.hibernate.SessionFactory
sessionFactory;
private static String configFile =
CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory =
configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory
%%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance.
Lazy initialize
* the SessionFactory if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws
HibernateException {
Session session = (Session) threadLocal.get();
if (session == null ||
!session.isOpen()) {
if (sessionFactory
== null) {
rebuildSessionFactory();
}
session =
(sessionFactory != null) ?
sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void
rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory =
configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory
%%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws
HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static
org.hibernate.SessionFactory getSessionFactory()
{
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the
next call
*/
public static void setConfigFile(String
configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration
getConfiguration() {
return configuration;
}
}
So if there is any help needed click contact us
above to send message to us.
/*
Directory structure
Firsthibernate
->
s2s
->gateway
->example
->simpleobj.hbm.xml
->simpleobj.class (pojo class)
->hibernate
->HibernateSessionFactory
->Sessionfactory util
WEB_INF
->lib
hibernate.cfg.xml
In lib folder
put all libraries files as mentioned below if your lib jars of hibernate located in root folder ./WEB-INF/lib
or
give appropriate path.
Example path:
E:/firsthibernate>h.bat
E:/firsthibernate>set classpath=./WEB-INF\lib\mysql-connector-java-3.
0.16-ga-bin.jar;./WEB-INF\lib\antlr-2.7.6.jar;./WEB-INF\lib\hibernate-search.jar
;./WEB-INF\lib\hibernate-commons-annotations.jar;./WEB-INF\lib\hibernate-annotat
ions.jar;./WEB-INF\lib\log4j.jar;./WEB-INF\lib\ejb3-persistence.jar;./WEB-INF\li
b\slf4j-log4j12.jar;./WEB-INF\lib\slf4j-api.jar;./WEB-INF\lib\commons-collection
s.jar;./WEB-INF\lib\dom4j.jar;./WEB-INF\lib\lucene-core.jar;./WEB-INF\lib\common
s-logging-1.0.4.jar;./WEB-INF\lib\hibernate-core.jar;./WEB-INF\lib\ehcache-1.1.j
ar;./WEB-INF\lib\xml-apis.jar;./WEB-INF\lib\javassist-3.4.GA.jar;./WEB-INF\lib\e
hcache-1.2.3.jar;./WEB-INF\lib\junit.jar;./WEB-INF\lib\hsqldb.jar;./WEB-INF\lib\
thirdparty-all.jar;./WEB-INF\lib\hibernate-testing.jar;./WEB-INF\lib\hibernate-e
ntitymanager.jar;./WEB-INF\lib\jdbc2_0-stdext.jar;./WEB-INF\lib\cleanimports.jar
;./WEB-INF\lib\connector.jar;./WEB-INF\lib\concurrent-1.3.2.jar;./WEB-INF\lib\ja
as.jar;./WEB-INF\lib\jta.jar;
E:/firsthibernate>javac *.java
E:/firsthibernate>java TestClient
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment
).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select max(id) from simpleobj
Hibernate: insert into simpleobj (name, taste, id) values (?, ?, ?)
Hibernate: select simpleobj0_.id as id0_, simpleobj0_.name as name0_, simpleobj0_.taste as t
aste0_ from simpleobj simpleobj0_
Names of users:Andrew
Names of users:safiq
Names of users:north
Names of users:simpleforest
Names of users:north
Names of users:north
Names of users:north
Names of users:simpleforest
Names of users:simpleforest
Names of users:north
Names of users:north
Names of users:north
Names of users:north
Names of users:north
Names of users:north
Names of users:north
Names of users:north
Names of users:simpleforest
Hibernate: update simpleobj set name=?, taste=? where id=?
Create Database named car in mysql
create table simpleobj with id,name,taste
To know about mysql click the mysql tab above.
compile all
Javac *.java in all folders
finally run java TestClient
output
---------
mysql> use car;
Database changed
mysql> select * from simpleobj;
+----+----------------------+------------+
| id | name | taste |
+----+----------------------+------------+
| 1 | Andrew | roaming |
| 2 | safiq | web |
| 3 | north | very sweet |
| 4 | simpleforest | very sweet |
| 5 | north | very sweet |
+----+----------------------+------------+
5 rows in set (0.02 sec)
mysql> select * from simpleobj;
+----+----------------------+------------+
| id | name | taste |
+----+----------------------+------------+
| 1 | Andrew | roaming |
| 2 | safiq | web |
| 3 | north | region |
| 4 | simpleforest | very sweet |
| 5 | north | region|
| 6 | north | original |
+----+----------------------+------------+
6 rows in set (0.02 sec)