There are so many,
Hibernate is data base independent, your code will work for all ORACLE,MySQL ,SQLServer etc. In case of JDBC query must be data base specific.
As Hibernate is set of Objects,you don't need to learn SQL language.You can treat TABLE as a Object.Only Java knowledge is need. In case of JDBC you need to learn SQL
Don't need Query tuning in case of Hibernate.If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance. In case of JDBC you need to tune your queries.
You will get benefit of Cache. Hibernate support two level of cache.First level and 2nd level.So you can store your data into Cache for better performance. In case of JDBC you need to implement your java cache.
Hibernate supports Query cache and It will provide the statistics about your query and database status. JDBC Not provides any statistics.
Development fast in case of Hibernate because you don't need to write queries.
No need to create any connection pool in case of Hibernate.You can use c3p0. In case of JDBC you need to write your own connection pool.
In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.
You can load your objects on start up using lazy=false in case of Hibernate. JDBC don't have such support.
Hibernate Supports automatic versioning of rows but JDBC Not.
If you don't have JTA and don't want to deploy it along with your application, you will usually have to fall back to JDBC transaction demarcation. Instead of calling the JDBC API you better use Hibernate's Transaction and the built-in session-per-request functionality.
To enable the thread-bound strategy in your Hibernate configuration:
set hibernate.transaction.factory_class
to org.hibernate.transaction.JDBCTransactionFactory
set hibernate.current_session_context_class
to thread
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// Do some work
session.load(...);
session.persist(...);
tx.commit(); // Flush happens automatically
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
finally {
session.close();
}
Both of these methods and saveOrUpdate() method are intended for reattaching a detached object.
The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object.
It is the best practice to use either session.update(..) or session.saveOrUpdate().
Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.
Each interaction with the persistent store occurs in a new Session. However, the same persistent instances are reused for each interaction with the database. The application manipulates the state of detached instances originally loaded in another Session and then "reassociates" them using Session.update() or Session.saveOrUpdate().
// foo is an instance loaded by a previous Session
foo.setProperty("bar");
session = factory.openSession();
session.saveOrUpdate(foo);
session.flush();
session.connection().commit();
session.close();
You may also call lock() instead of update() and use LockMode.READ (performing a version check, bypassing all caches) if you are sure that the object has not been modified.
The "current session" refers to a Hibernate Session bound by Hibernate behind the scenes, to the transaction scope.
A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends.
It is also flushed automatically before the transaction commits. You can call getCurrentSession() as often and anywhere you want as long as the transaction runs.
To enable this strategy in your Hibernate configuration:
Set hibernate.transaction.manager_lookup_class
to a lookup strategy for your JEE container
Set hibernate.transaction.factory_class
to org.hibernate.transaction.JTATransactionFactory
Only the Session that you obtained with sf.getCurrentSession() is flushed and closed automatically.
Example :
try {
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
tx.begin();
// Do some work
sf.getCurrentSession().createQuery(...);
sf.getCurrentSession().persist(...);
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
If you decide to use manage the Session yourself the go for sf.openSession(), you have to flush() and close() it.
It does not flush and close() automatically.
Example :
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
Session session = factory.openSession();
try {
tx.begin();
// Do some work
session.createQuery(...);
session.persist(...);
session.flush(); // Extra work you need to do
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
finally {
session.close(); // Extra work you need to do
}
In the resource bundle file, you can define a template like :
errors.required={0} is required.
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.custform","First Name"));
Then the Error message is : First Name is required.
Other constructors are :
public ActionError(String key, Object value0, Object value1)
. . .
public ActionError(String key, Object[] values);
SessionFactory sf = new Configuration()
.addFile("Item.hbm.xml")
.addFile("Bid.hbm.xml")
.buildSessionFactory();
User Session.connection()
method to get JDBC Connection.
Step 1. Put Hibernate properties in the classpath.
Step 2. Put .hbm.xml in class path.
Code is Here to create session ...
package com.dao;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
/**
*
* @author Satya Das
*/
public class HibernateUtil {
protected static final Logger logger=Logger.getLogger(HibernateUtil.class);
public static String appHome = "No";
private static SessionFactory sessionFactory;
private static final ThreadLocal threadSession = new ThreadLocal();
private static final ThreadLocal threadTransaction = new ThreadLocal();
/**
* Initialize Hibernate Configuration
*/
public static void initMonitor(){
logger.info("Hibernate configure");
try {
logger.info("appHome"+appHome);
String path_properties = appHome+File.separatorChar+"hibernate.properties";
String path_mapping = appHome+File.separatorChar+"mapping_classes.mysql.hbm.xml";
//String ecache = appHome+File.separatorChar+"ehcache.xml";
Properties propHibernate = new Properties();
propHibernate.load(new FileInputStream(path_properties));
Configuration configuration = new Configuration();
configuration.addFile(path_mapping);
configuration.setProperties(propHibernate);
/* try {
CacheManager.create(ecache);
} catch (CacheException e) {
// logger.logError(e);
}*/
sessionFactory = configuration.buildSessionFactory();
} catch (Throwable ex) {
logger.error("Exception in initMonitor",ex);
throw new ExceptionInInitializerError(ex);
}
}
/**
* @return a Session Factory Object
*/
public static SessionFactory getSessionFactory() {
logger.info("Inside getSessionFactory method");
try {
if (sessionFactory == null) {
initMonitor();
}else {
//sessionFactory.getStatistics().logSummary();
}
} catch (Exception e) {
logger.error("Exception in getSessionFactory",e);
}
return sessionFactory;
}
/**
* @return Session . Start a Session
*/
public static Session getSession() {
Session s = (Session) threadSession.get();
logger.debug("session"+s);
if (s == null) {
s = getSessionFactory().openSession();
threadSession.set(s);
logger.debug("session 1 $"+s);
}
return s;
}
/**
* Close Session
*/
public static void closeSession(){
Session s = (Session) threadSession.get();
threadSession.set(null);
if (s != null && s.isOpen()) {
s.flush();
s.close();
}
}
/**
* Start a new database transaction.
*/
public static void beginTransaction(){
Transaction tx = null;
if (tx == null) {
tx = getSession().beginTransaction();
threadTransaction.set(tx);
}
}
/**
* Commit the database transaction.
*/
public static void commitTransaction(){
Transaction tx = (Transaction) threadTransaction.get();
try {
if ( tx != null ) {
tx.commit();
}
threadTransaction.set(null);
} catch (HibernateException ex) {
rollbackTransaction();
throw ex;
}
}
/**
* Rollback the database transaction.
*/
public static void rollbackTransaction(){
Transaction tx = (Transaction) threadTransaction.get();
try {
threadTransaction.set(null);
if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
tx.rollback();
}
} finally {
closeSession();
}
}
}
transient :
The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value).
persistent :
The instance is currently associated with a persistence context. It has a persistent identity (primary key
value) and, perhaps, a corresponding row in the database. For a particular persistence context, Hibernate
guarantees that persistent identity is equivalent to Java identity (in-memory location of the object).
detached :
The instance was once associated with a persistence context, but that context was closed, or the instance
was serialized to another process. It has a persistent identity and, perhaps, a corresponding row in the database.
For detached instances, Hibernate makes no guarantees about the relationship between persistent identity and Java identity.
SessionFactory (org.hibernate.SessionFactory) :
A threadsafe (immutable) cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider. Might hold an optional (second-level) cache of data that is reusable between transactions, at a process- or cluster-level.
Session (org.hibernate.Session) :
A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC connection. Factory for Transaction. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier.
Persistent objects and collections Short-lived, single threaded objects containing persistent state and business function. These might be ordinary JavaBeans/POJOs, the only special thing about them is that they are currently associated with (exactly one) Session. As soon as the Session is closed, they will be detached and free to use in any application layer (e.g. directly as data transfer objects to and from presentation).
Transient and detached objects and collections Instances of persistent classes that are not currently associated with a Session. They may have been instantiated by the application and not (yet) persisted or they may have been instantiated by a closed Session.
Transaction (org.hibernate.Transaction) :
(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. Abstracts application from underlying JDBC, JTA or CORBA transaction. A Session might span several Transactions in some cases. However, transaction demarcation, either using the underlying API or Transaction, is never optional!
Architecture Hibernate 3.0.2 9
ConnectionProvider (org.hibernate.connection.ConnectionProvider) :
(Optional) A factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource or DriverManager. Not exposed to application, but can be extended/implemented by the developer.
TransactionFactory (org.hibernate.TransactionFactory) :
(Optional) A factory for Transaction instances. Not exposed to the application, but can be extended/ implemented by the developer.
Extension Interfaces :
Hibernate offers many optional extension interfaces you can implement to customize the behavior of your persistence layer. See the API documentation for details.