Hibernate
Hibernate
-----------------------
Hibernate is a Java framework that simplifies the development of Java application
to interact with the database.
It is an open source, lightweight, ORM (Object Relational Mapping) tool. Hibernate
implements the specifications of JPA (Java Persistence API) for data persistence.
2) ORM Tool
------------
An ORM tool simplifies the data creation, data manipulation and data access. It is
a programming technique that maps the object to the data stored in the database.
The ORM tool internally uses the JDBC API to interact with the database.
2) Fast Performance
The performance of hibernate framework is fast because cache is internally used in
hibernate framework.
There are two types of cache in hibernate framework first level cache and second
level cache. First level cache is enabled by default.
SessionFactory
The SessionFactory is a factory of session and client of ConnectionProvider. It
holds second level cache (optional) of data.
The org.hibernate.SessionFactory interface provides factory method to get the
object of Session.
Session
The session object provides an interface between the application and data stored in
the database. It is a short-lived object and wraps the JDBC connection.
It is factory of Transaction, Query and Criteria. It holds a first-level cache
(mandatory) of data. The org.hibernate.Session interface provides methods to
insert,
update and delete the object. It also provides factory methods for Transaction,
Query and Criteria.
Transaction
The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.
ConnectionProvider
It is a factory of JDBC connections. It abstracts the application from
DriverManager or DataSource. It is optional.
TransactionFactory
It is a factory of Transaction. It is optional
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
5) Create the Configuration file
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
}
Hibernate Annotations are based on the JPA 2 specification and supports all the
features.
All the JPA annotations are defined in the javax.persistence package. Hibernate
EntityManager implements the interfaces and life cycle defined by the JPA
specification.
The core advantage of using hibernate annotation is that you don't need to create
mapping (hbm) file. Here, hibernate annotations are used to provide the meta data.
hibernate.cfg.xml
------------------
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.javatpoint.mypackage.Employee"/>
</session-factory>
</hibernate-configuration>
assigned
increment
sequence
hilo
native
identity
seqhilo
uuid
guid
select
foreign
sequence-identity
1) assigned
For example:
....
<hibernate-mapping>
<class ...>
<id ...>
<generator class="assigned"></generator>
</id>
.....
</class>
</hibernate-mapping>
3) sequence
For defining your own sequence, use the param subelement of generator.
.....
<id ...>
<generator class="sequence">
<param name="sequence">your_sequence_name</param>
</generator>
</id>
.....
Logging enables the programmer to write the log details into a file permanently.
Log4j and Logback frameworks can be used in hibernate framework to support logging.
Levels Description
OFF This level is used to turn off logging.
WARNING This is a message level that indicates a problem.
SEVERE This is a message level that indicates a failure.
INFO This level is used for informational messages.
CONFIG This level is used for static configuration messages.
log4j.properties
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\javatpointhibernate.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
a) Question.java
package com.javatpoint;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name="q5991")
public class Question {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
private int id;
private String qname;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="qid")
@OrderColumn(name="type")
private List<Answer> answers;
//sertters and getters
}
b) Answer.java
package com.javatpoint;
import javax.persistence.*;
@Entity
@Table(name="ans5991")
public class Answer {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.javatpoint.Question"/>
</session-factory>
</hibernate-configuration>
D) StoreData.java
package com.javatpoint;
import java.util.ArrayList;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class StoreData {
public static void main(String[] args) {
StandardServiceRegistry ssr=new
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
session.persist(question1);
session.persist(question2);
t.commit();
session.close();
System.out.println("success");
}
}
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
//some action
tx.commit();
Advantage of HQL
There are many advantages of HQL. They are as follows:
database independent
supports polymorphic queries
easy to learn for Java Programmer
The query interface provides many methods. There is given commonly used methods:
int status=q.executeUpdate();
System.out.println(status);
tx.commit();
@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)
}
)
SessionFactory holds the second level cache data. It is global for all the session
objects and not enabled by default.
a) Employee.java
@Entity
@Table(name="emp1012")
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
public class Employee {
@Id
private int id;
private String name;
--
--
--
b) hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property
name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="cache.use_second_level_cache">true</property>
<property
name="cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory<
/property>
<mapping class="com.javatpoint.Employee"/>
</session-factory>
</hibernate-configuration>
c) FetchTest.java
------------------
Session session1=factory.openSession();
Employee emp1=(Employee)session1.load(Employee.class,121);
System.out.println(emp1.getId()+" "+emp1.getName()+" "+emp1.getSalary());
session1.close();
Session session2=factory.openSession();
Employee emp2=(Employee)session2.load(Employee.class,121);
System.out.println(emp2.getId()+" "+emp2.getName()+" "+emp2.getSalary());
session2.close();
Second level cache is applicaton level cache.
Note: We are loading same employee entity for twice, Now the db call will be
executed for only once and the second time it will be fetched from second level
cache.
So performance will be improved.
But if we are going to integrate the hibernate application with spring, we don't
need to create the hibernate.cfg.xml file.
We can provide all the information in the applicationContext.xml file.
//creating configuration
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
t.commit();//transaction is commited
session.close();
As you can see in the code of sole hibernate, you have to follow so many steps.
Example:
-------------
2) Employee.java
It is a simple POJO class. Here it works as the persistent class for hibernate.
package com.javatpoint;
3) employee.hbm.xml
This mapping file contains all the information of the persistent class.
<hibernate-mapping>
<class name="com.javatpoint.Employee" table="emp558">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
4) EmployeeDao.java
It is a java class that uses the HibernateTemplate class method to persist the
object of Employee class.
package com.javatpoint;
import org.springframework.orm.hibernate3.HibernateTemplate;
import java.util.*;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
//method to save employee
public void saveEmployee(Employee e){
template.save(e);
}
//method to update employee
public void updateEmployee(Employee e){
template.update(e);
}
//method to delete employee
public void deleteEmployee(Employee e){
template.delete(e);
}
//method to return one employee of given id
public Employee getById(int id){
Employee e=(Employee)template.get(Employee.class,id);
return e;
}
//method to return all employees
public List<Employee> getEmployees(){
List<Employee> list=new ArrayList<Employee>();
list=template.loadAll(Employee.class);
return list;
}
}
5) applicationContext.xml
In this file, we are providing all the informations of the database in the
BasicDataSource object. This object is used in the LocalSessionFactoryBean class
object,
containing some other informations such as mappingResources and
hibernateProperties. The object of LocalSessionFactoryBean class is used in the
HibernateTemplate class. Let's see the code of applicationContext.xml file.
hibernate template
File: applicationContext.xml
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
</beans>
6) InsertTest.java
This class uses the EmployeeDao class object and calls its saveEmployee method by
passing the object of Employee class.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
EmployeeDao dao=(EmployeeDao)factory.getBean("d");
dao.saveEmployee(e);
}
}