Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Monday, July 5, 2021

Hibernate in Java- Overview

Hibernate in Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Exam Prep, Oracle Java Certification, Oracle Java Career

Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is an open source persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application.

Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves the developer from 95% of common data persistence related programming tasks.

Hibernate sits between traditional Java objects and database server to handle all the works in persisting those objects based on the appropriate O/R mechanisms and patterns.

Hibernate in Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Exam Prep, Oracle Java Certification, Oracle Java Career

Hibernate Advantages


◉ Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code.

◉ Provides simple APIs for storing and retrieving Java objects directly to and from the database.

◉ If there is change in the database or in any table, then you need to change the XML file properties only.

◉ Abstracts away the unfamiliar SQL types and provides a way to work around familiar Java Objects.

◉ Hibernate does not require an application server to operate.

◉ Manipulates Complex associations of objects of your database.

◉ Minimizes database access with smart fetching strategies.

◉ Provides simple querying of data.

Supported Databases


Hibernate supports almost all the major RDBMS. Following is a list of few of the database engines supported by Hibernate −

◉ HSQL Database Engine

◉ DB2/NT

◉ MySQL

◉ PostgreSQL

◉ FrontBase

◉ Oracle

◉ Microsoft SQL Server Database

◉ Sybase SQL Server

◉ Informix Dynamic Server

Supported Technologies


Hibernate supports a variety of other technologies, including −

◉ XDoclet Spring

◉ J2EE

◉ Eclipse plug-ins

◉ Maven

Source: tutorialspoint.com

Wednesday, July 29, 2020

Difference between JDBC and Hibernate in Java

Oracle JDBC, Oracle Hibernate, Oracle Java Tutorial and Material, Oracle Java Exam Prep

Java is one of the most powerful and popular server-side languages in the current scenario. One of the main features of a server-side language is the ability to communicate with the databases. In this article, let’s understand the difference between two ways of connecting to the database (i.e.) JDBC and Hibernate.

Before getting into the differences, let us first understand what each of them actually means.

JDBC: JDBC stands for Java Database Connectivity. It is a java application programming interface to provide a connection between the Java programming language and a wide range of databases (i.e), it establishes a link between the two so that a programmer could send data from Java code and store it in the database for future use.

Hibernate: Hibernate is an open-source, non-invasive, light-weight java ORM(Object-relational mapping) framework to develop objects which are independent of the database software and make independent persistence logic in all JAVA, JEE. It simplifies the interaction of java applications with databases. Hibernate is an implementation of JPA(Java Persistence API).

The following table describes the differences:

JDBC   HIBERNATE 
In JDBC, one needs to write code to map the object model’s data representation to the schema of the relational model.  Hibernate maps the object model’s data to the schema of the database itself with the help of annotations. 
JDBC enables developers to create queries and update data to a relational database using the Structured Query Language (SQL).  Hibernate uses HQL (Hibernate Query Language) which is similar to SQL but understands object-oriented concepts like inheritance, association etc. 
JDBC code needs to be written in a try catch block as it throws checked exception(SQLexception).  Whereas Hibernate manages the exceptions itself by marking them as unchecked. 
JDBC is database dependent i.e. one needs to write different codes for different database.  Whereas Hibernate is database independent and same code can work for many databases with minor changes. 
Creating associations between relations is quite hard in JDBC.  Associations like one-to-one, one-to-many, many-to-one, and many-to-many can be acquired easily with the help of annotations. 

Friday, July 10, 2020

Hibernate and Spring Integration

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Guides

We can simply integrate hibernate application with spring application.

In hibernate framework, we provide all the database information hibernate.cfg.xml file.

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.

Advantage of Spring framework with hibernate


The Spring framework provides HibernateTemplate class, so you don't need to follow so many steps like create Configuration, BuildSessionFactory, Session, beginning and committing transaction etc.

So it saves a lot of code.

Understanding problem without using spring:

Let's understand it by the code of hibernate given below:

//creating configuration
Configuration cfg=new Configuration(); 
cfg.configure("hibernate.cfg.xml"); 
 
//creating seession factory object 
SessionFactory factory=cfg.buildSessionFactory(); 
 
//creating session object 
Session session=factory.openSession(); 
 
//creating transaction object 
Transaction t=session.beginTransaction(); 
     
Employee e1=new Employee(111,"arun",40000); 
session.persist(e1);//persisting the object 
 
t.commit();//transaction is commited 
session.close(); 

As you can see in the code of sole hibernate, you have to follow so many steps.

Solution by using HibernateTemplate class of Spring Framework:

Now, you don't need to follow so many steps. You can simply write this:

Employee e1=new Employee(111,"arun",40000); 
hibernateTemplate.save(e1);

Methods of HibernateTemplate class


Let's see a list of commonly used methods of HibernateTemplate class.

No. Method  Description 
void persist(Object entity)   persists the given object.
Serializable save(Object entity)   persists the given object and returns id. 
void saveOrUpdate(Object entity)   persists or updates the given object. If id is found, it updates the record otherwise saves the record.
void update(Object entity)   updates the given object.
void delete(Object entity)   deletes the given object on the basis of id. 
Object get(Class entityClass, Serializable id)   returns the persistent object on the basis of given id. 
Object load(Class entityClass, Serializable id)   returns the persistent object on the basis of given id. 
List loadAll(Class entityClass)   returns the all the persistent objects. 

Steps


Let's see what are the simple steps for hibernate and spring integration:

1. create table in the database It is optional.
2. create applicationContext.xml file It contains information of DataSource, SessionFactory etc.
3. create Employee.java file It is the persistent class
4. create employee.hbm.xml file It is the mapping file.
5. create EmployeeDao.java file It is the dao class that uses HibernateTemplate.
6. create InsertTest.java file It calls methods of EmployeeDao class.

Example of Hibernate and spring integration


In this example, we are going to integrate the hibernate application with spring. Let's see the directory structure of spring and hibernate example.

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Guides

1) create the table in the database

In this example, we are using the Oracle as the database, but you may use any database. Let's create the table in the oracle database

CREATE TABLE  "EMP558"   
   (    "ID" NUMBER(10,0) NOT NULL ENABLE,   
    "NAME" VARCHAR2(255 CHAR),   
    "SALARY" FLOAT(126),   
     PRIMARY KEY ("ID") ENABLE  
   )  
/  

2) Employee.java

It is a simple POJO class. Here it works as the persistent class for hibernate.

package com.oraclejavacertified;  
  
public class Employee {  
private int id;  
private String name;  
private float salary;  
  
//getters and setters  
  
}  

3) employee.hbm.xml

This mapping file contains all the information of the persistent class.

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  
<hibernate-mapping>  
<class name="com.oraclejavacertified.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.oraclejavacertified;  
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.

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Guides

File: applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  
  
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
        <property name="driverClassName"  value="oracle.jdbc.driver.OracleDriver"></property>  
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>  
        <property name="username" value="system"></property>  
        <property name="password" value="oracle"></property>  
    </bean>  
      
    <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>  
      
    <bean id="d" class="com.oraclejavacertified.EmployeeDao">  
    <property name="template" ref="template"></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.oraclejavacertified;  
  
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;  
  
public class InsertTest {  
public static void main(String[] args) {  
      
    Resource r=new ClassPathResource("applicationContext.xml");  
    BeanFactory factory=new XmlBeanFactory(r);  
      
    EmployeeDao dao=(EmployeeDao)factory.getBean("d");  
      
    Employee e=new Employee();  
    e.setId(114);  
    e.setName("varun");  
    e.setSalary(50000);  
      
    dao.saveEmployee(e);  
      
}  

Enabling automatic table creation, showing sql queries etc.

You can enable many hibernate properties like automatic table creation by hbm2ddl.auto etc. in applicationContext.xml file. Let's see the code:

<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>  

If you write this code, you don't need to create table because table will be created automatically.