Hibernate One-To-One Mapping Using Java Annotations Tutorial with Examples

One To One Relationship

A one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity. Consider the following relationship:
Hibernate One-To-One Mapping Using Java Annotations Tutorial with Examples

According to the relationship each STUDENT should have a unique STUDENT_ADDRESS. Hence we will need two tables namely STUDENT and STUDENT_ADDRESS to create this relation. In Hibernate, one-to-one relationship between entities can be created by 3 different techniques. In each technique though @OneToOne annotation has to be used. These techniques are:

Using shared primary key

In this technique, hibernate will ensure that it will use a common primary key value in both the tables. This way primary key of entity STUDENT can safely be assumed the primary key of entity STUDENT_ADDRESS also. The example demonstrated in this post is using shared primary key.

Using foreign key association

In this association, a foreign key column is created in the owner entity. For example, if we make STUDENT as owner entity, then a extra column “ADDRESS_ID” will be created in STUDENT table. This column will store the foreign key for STUDENT_ADDRESS table.

Using a common join table

In this association, the join table will have two foreign key columns (i.e) it will have both the primary key columns from the two entity tables (for example STUDENT_ID and ADDRESS_ID from STUDENT and STUDENT_ADDRESS entity tables respectively). One of the foreign keys will serve as the primary key for the join table. An unique constraint will be applied on the remaining foreign key column and hence both the foreign key columns will not have the duplicate values.

Creating Database

Before we start lets create a simple database and table to apply hibernate operations on. Copy and Paste the following sql query in your query editor and execute.
CREATE table STUDENT (student_id bigint identity NOT NULL PRIMARY KEY,
rollno varchar(20),
firstname varchar(50),
lastname varchar(50),
course varchar(50))

CREATE TABLE STUDENT_ADDRESS (student_id bigint NOT NULL PRIMARY KEY FOREIGN KEY REFERENCES STUDENT (student_id),
address varchar(100) DEFAULT NULL, 
city varchar(100) DEFAULT NULL, state varchar(100) DEFAULT NULL, 
country varchar(100) DEFAULT NULL 
)


NOTE : Above script is written for SQL Server, you can change accordingly for different DB.

Adding Hibernate Jars

Download latest Hibernate jars from here http://hibernate.org/ and add to your classpath.

Create Model Classes (Shared primary key technique)

As a next step let’s create the model classes Student.java and StudentAddress.java using Annotations. @PrimaryKeyJoinColumn is the main annotation to be used in shared primary key technique. The model classes are as below

Student.java
package com.tutorialsdesk.hibernate.bean;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType;
import javax.persistence.Id; 
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;    
import javax.persistence.UniqueConstraint;
@Entity 
@Table(name="STUDENT",uniqueConstraints = { @UniqueConstraint(columnNames = "student_id") }) 

public class Student implements Serializable {

 private static final long serialVersionUID = 5502738307095121008L;

 @Id   
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name = "student_id")  
 private int id;
 
 @Column(name="rollno")   
 private String rollno;
 
 @Column(name="firstname")   
 private String firstname;
 
 @Column(name="lastname")     
 private String lastname;
 
 @Column(name="course")   
 private String course;
    
    @OneToOne(cascade = CascadeType.ALL)  
 @PrimaryKeyJoinColumn 
 private StudentAddress address;
    
    public Student(){
     
    }
    
 public Student(String rollno, String firstname, String lastname,
   String course, StudentAddress address) {
  super();
  this.rollno = rollno;
  this.firstname = firstname;
  this.lastname = lastname;
  this.course = course;
  this.address = address;
 }



 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getRollno() {
  return rollno;
 }

 public void setRollno(String rollno) {
  this.rollno = rollno;
 }

 public String getFirstname() {
  return firstname;
 }

 public void setFirstname(String firstname) {
  this.firstname = firstname;
 }

 public String getLastname() {
  return lastname;
 }

 public void setLastname(String lastname) {
  this.lastname = lastname;
 }

 public String getCourse() {
  return course;
 }

 public void setCourse(String course) {
  this.course = course;
 }

 public StudentAddress getAddress() {
  return address;
 }

 public void setAddress(StudentAddress address) {
  this.address = address;
 }


 
}


In the above file we see that we have used @PrimaryKeyJoinColumn for the Address entity. Following if a piece of code from the above file:
@OneToOne(cascade = CascadeType.ALL)  
@PrimaryKeyJoinColumn 
private StudentAddress address;



StudentAddress.java
package com.tutorialsdesk.hibernate.bean;

import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;



@Entity 
@Table(name = "STUDENT_ADDRESS", uniqueConstraints = { @UniqueConstraint(columnNames = "student_id") })  

public class StudentAddress implements Serializable {

 /**
  * 
  */
 private static final long serialVersionUID = 7871228112490214979L;

 @Id
 @Column(name = "student_id", unique = true, nullable = false)
 @GeneratedValue(generator = "gen")
 @GenericGenerator(name = "gen", strategy = "foreign",parameters = @Parameter(name = "property", value = "student"))
 private int studentId;
 
 @Column(name="address")
 private String address;
 
 @Column(name="city")
 private String city;
 
 @Column(name="state")
 private String state;
 
 @Column(name="country")
 private String country;
 
 @OneToOne(mappedBy = "address", cascade = CascadeType.ALL)  
 private Student student;  

 public StudentAddress() {
  
 }  

 public int getStudentId() {
  return studentId;
 }
 public StudentAddress(String address, String city, String state,
   String country) {
  super();
  this.address = address;
  this.city = city;
  this.state = state;
  this.country = country;
 }
 
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }
 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getState() {
  return state;
 }
 public void setState(String state) {
  this.state = state;
 }
 public String getCountry() {
  return country;
 }
 public void setCountry(String country) {
  this.country = country;
 }

 public Student getStudent() {
  return student;
 }

 public void setStudent(Student student) {
  this.student = student;
 }
 
}


Here we see that Address entity will remain dependent on owner entity for the mapping. Following is a piece of code from the above file:
@OneToOne(mappedBy = "address", cascade = CascadeType.ALL)  
private Student student;  

Adding Hibernate Configuration file

The hibernate.cfg.xml is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
        <property name="hibernate.connection.password">yourpassword</property>
        <property name="hibernate.connection.url">jdbc:jtds:sqlserver://localhost:1433/yourdbname</property>
        <property name="hibernate.connection.username">yourusername</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
     <property name="connection.pool_size">1</property>
        <property name="hbm2ddl.auto">create</property>
        <property name="show_sql">true</property>  
  <property name="format_sql">true</property>  
        <mapping class="com.tutorialsdesk.hibernate.bean.Student"/>
        <mapping class="com.tutorialsdesk.hibernate.bean.StudentAddress"/>
        
    </session-factory>
</hibernate-configuration>



In the above file we have set the database connection to SQL Server database . The show_sql option, if set to true will display all the executed SQL queries on the console. The property hbm2ddl.auto , if set to create, creates the schema, destroying the previous data.

Note : In case you want to use any other database then, you need to change these properties – “dialect”, “connection.driver_class”, “connection.url”, “connection.username”, and “connection.password”.

Also we have added the Annotation based entity classes Student.java and StudentAddress.java to the above file.

Create Utility class

Next, we will write a utility class to take care of Hibernate start up and retrieve the session easily. We will write the file HibernateUtil.java as below:
package com.tutorialsdesk.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration; 

 
public class HibernateUtil {
 
 private static final SessionFactory sessionFactory = buildSessionFactory();

  private static SessionFactory buildSessionFactory() {
   try {
    return new AnnotationConfiguration().configure().buildSessionFactory(); 
   } catch (Throwable ex) {
    System.err.println("Initial SessionFactory creation failed." + ex);
    throw new ExceptionInInitializerError(ex);
   }
  }

  public static SessionFactory getSessionFactory() {
   return sessionFactory;
  }

  public static void shutdown() {
   getSessionFactory().close();
  }


}


Main AnnotationTest class

This class tests the one-to-one relationship by creating and listing the student details and corresponding addresses as below:
package com.tutorialsdesk.hibernate;

import java.util.ArrayList;

import org.hibernate.*;

import com.tutorialsdesk.hibernate.bean.Student;
import com.tutorialsdesk.hibernate.bean.StudentAddress;

public class AnnotationTest {
public static void main(String[] args) {
 
 AnnotationTest test=new AnnotationTest();
 StudentAddress sa1 = new StudentAddress("C-42","Noida","UP","IN");
 StudentAddress sa2 = new StudentAddress("D-61","Agra","UP","IN");
 Student s1=new Student("CS1","Ankit","Yadav","MCA",sa1);
 Student s2=new Student("CS2","Rahul","Jena","B.Tech",sa1);
 sa1.setStudent(s1);
 s1.setAddress(sa1); 
 
 sa2.setStudent(s2);
 s2.setAddress(sa2); 
 
 
 test.saveStudent(s1);
 test.saveStudent(s2);
 
 test.getStudent();
 System.out.println("successfully saved");
}
public void saveStudent(Student student) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   session.save(student);

   session.getTransaction().commit();
   
  }

  public void updateStudent(Student student) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   session.merge(student);

   session.getTransaction().commit();
  }

  public void deleteStudent(Student student) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   session.delete(student);

   session.getTransaction().commit();
  }

  public void getStudent() {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   @SuppressWarnings("unchecked")
 ArrayList<Student> list = (ArrayList<Student>) session.createQuery("from Student").list();
   if (list != null) {
    for (int i = 0; i < list.size(); i++) {
     System.out.println("User ID : " + list.get(i).getId());
     System.out.println("User First Name : "+ list.get(i).getFirstname());
     System.out.println("User Last Name : "+ list.get(i).getLastname());
     System.out.println("User Roll No : " + list.get(i).getRollno());
     System.out.println("User Course : " + list.get(i).getCourse());
     System.out.println("User Address : " + list.get(i).getAddress().getAddress() + ","+ list.get(i).getAddress().getCity() +"\n"+ list.get(i).getAddress().getState() +"\n"+ list.get(i).getAddress().getCountry());
    
   }
   }
   session.getTransaction().commit();
  }

}

Here the saveStudent() method is used to save a new Person object and Address object to the database. In the saveStudent() method a new object of the Student class is created and the name value and address is set. The studentId value is auto generated so the value need not be set here. We then save the Student object to the Address object. The session.save() method is used to persist the value in the database and once the value is saved, the id value (Primary key) is returned. Once the object is saved, the transaction is committed. If any exception occurs then the transaction is rolledback. The transaction ends either through commit or rollback action. Once the transaction ends the session is closed.

The getStudent() method is used to list name of each student in STUDENT table and their corresponding addresses from STUDENT_ADDRESS table. Here we use Hibernate Query Language (HQL). The query “from Student” returns a list of all the data in the STUDENT table and their corresponding addresses from STUDENT_ADDRESS table. Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list the data from Student and corresponding StudentAddress table and hence display them on the console.

Execute the above code

Execute the above code to demonstrate Hibernate One-To-One mapping.

Using Foreign Key Technique

In such a association, refer the Address entity in Student class as follows:
@OneToOne
@JoinColumn(name="addressId")
private Address address;

If no @JoinColumn is declared on the owner entity, the defaults apply. A join column(s) will be created in the owner entity table and its name will be the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column(s) in the owned side.

In a bidirectional relationship, one of the sides has to be the owner entity. The owner is responsible for the association column(s) update. To declare a side as not responsible for the relationship, the attribute mappedBy is used. mappedBy refers to the property name of the association on the owner side. Following is the example code:

@OneToOne(mappedBy="address")  
private Person person; 

Using a Common Join Table

In this technique, main annotation to be used is @JoinTable. This annotation is used to define the new table name (this is mandatory) and foreign keys from both of the tables. Folllowing is the example code:
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name="STU_ADDRESS", joinColumns = @JoinColumn(name="student_id"),
inverseJoinColumns = @JoinColumn(name="address_Id"))
private Address address;

@JoinTable annotation is used in Person class. It declares that a new table STU_ADDRESS will be created with two columns student_Id (primary key of STUDENT table) and addressId (primary key of STUDENT_ADDRESS table).
Hibernate One-To-One Mapping Using Java Annotations Tutorial with Examples

Hope we are able to explain you Hibernate One-To-One Mapping Using Java Annotations, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Sample Web Application with Hibernate Tutorial with examples

Here, we are going to create a web application with hibernate. For creating the web application, we are using JSP for presentation logic, Bean class for representing data and DAO class for database codes.

Example to create web application using hibernate

Creating Database

Before we start lets create a simple database and table to apply hibernate operations on. Copy and Paste the following sql query in your query editor and execute.
CREATE table STUDENT (ID bigint identity,
rollno varchar(20),
firstname varchar(50),
lastname varchar(50),
course varchar(50),
address varchar(100))


NOTE : Above script is written for SQL Server, you can change accordingly for different DB.

Adding Hibernate Jars

Download latest Hibernate jars from here http://hibernate.org/ and add to your classpath.

Add hibernate.cfg.xml

It is a configuration file, containing informations about the database and mapping file.

put this file under root folder.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
        <property name="hibernate.connection.password">yourdbpassword</property>
        <property name="hibernate.connection.url">jdbc:jtds:sqlserver://localhost:1433/yourdbname</property>
        <property name="hibernate.connection.username">yourdbusername</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
     <property name="connection.pool_size">1</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.tutorialsdesk.hibernate.bean.Student"/>
        
    </session-factory>
</hibernate-configuration>


Adding Hibernate Utils class

This is a simple java class with a static method, we will use this class to get a session instance of hibernate session factory class.
package com.tutorialsdesk.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration; 

 
public class HibernateUtil {
 
 private static final SessionFactory sessionFactory = buildSessionFactory();

  private static SessionFactory buildSessionFactory() {
   try {
    return new AnnotationConfiguration().configure().buildSessionFactory(); 
   } catch (Throwable ex) {
    System.err.println("Initial SessionFactory creation failed." + ex);
    throw new ExceptionInInitializerError(ex);
   }
  }

  public static SessionFactory getSessionFactory() {
   return sessionFactory;
  }

  public static void shutdown() {
   getSessionFactory().close();
  }


}


Adding bean class file

This is a simple pojo consisting of an Student object, we will map this class to relational database using hibernate utilities.

@Entity annotation marks this class as an entity.

@Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name bydefault.

@Id annotation marks the identifier for this entity.

@Column annotation specifies the details of the column for this property or field. If @Column annotation is not specified, property name will be used as the column name bydefault.

package com.tutorialsdesk.hibernate.bean;

import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
import javax.persistence.Table;    
@Entity 
@Table(name="STUDENT") 

public class Student {

 @Id    
 @GeneratedValue   
 private int id;
 
 @Column(name="rollno")   
 private String rollno;
 
 @Column(name="firstname")   
 private String firstname;
 
 @Column(name="lastname")     
 private String lastname;
 
 @Column(name="course")   
 private String course;
 
 @Column(name="address")   
 private String address;
 
 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getRollno() {
  return rollno;
 }

 public void setRollno(String rollno) {
  this.rollno = rollno;
 }

 public String getFirstname() {
  return firstname;
 }

 public void setFirstname(String firstname) {
  this.firstname = firstname;
 }

 public String getLastname() {
  return lastname;
 }

 public void setLastname(String lastname) {
  this.lastname = lastname;
 }

 public String getCourse() {
  return course;
 }

 public void setCourse(String course) {
  this.course = course;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }


 
}


StudentDao.java

This is simple java class containing main method to start execution, see the implementation to identify hibernate working in create, retrieve, update and delete operations.
package com.tutorialsdesk.hibernate;

import java.util.ArrayList;
import org.hibernate.*;
import com.tutorialsdesk.hibernate.bean.Student;

public class StudentDao {

 public static void saveUser(Student student) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   session.save(student);

   session.getTransaction().commit();
  }

  public void updateUser(Student student) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   session.merge(student);

   session.getTransaction().commit();
  }

  public void deleteUser(Student student) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   session.delete(student);

   session.getTransaction().commit();
  }

  public void getUser() {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   ArrayList<Student> list = (ArrayList<Student>) session.createQuery("from Student").list();
   if (list != null) {
    for (int i = 0; i < list.size(); i++) {
     System.out.println("User ID : " + list.get(i).getId());
     System.out.println("User First Name : "+ list.get(i).getFirstname());
     System.out.println("User Last Name : "+ list.get(i).getLastname());
     System.out.println("User Roll No : " + list.get(i).getRollno());
     System.out.println("User Address : " + list.get(i).getCourse());
    
   }
   }
   session.getTransaction().commit();
  }

}

Add index.jsp

This page gets input from the user and sends it to the register.jsp file using post method.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="register.jsp" method="post">
Roll Number:<input type="text" name="rollno"/><br><br/>
First Name:<input type="text" name="firstname"/><br><br/>
Last Name:<input type="text" name="lastname"/><br><br/>
Course:<input type="text" name="course"/><br><br/>
Address:<input type="text" name="address"/><br><br/>
<input type="submit" value="register"/>"

</form>
</body>
</html>

Add register.jsp

This file gets all request parameters and stores this information into an object of User class. Further, it calls the register method of UserDao class passing the User class object.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%@page import="com.tutorialsdesk.hibernate.StudentDao"%>

<jsp:useBean id="obj" class="com.tutorialsdesk.hibernate.bean.Student">
</jsp:useBean>
<jsp:setProperty property="*" name="obj"/>

<%
StudentDao.saveUser(obj);
out.print("You are successfully registered");
%>
</body>
</html>

Final Project Structure

Your final Project Structure under webapps folder will be as follows
Sanmple Web Application with Hibernate Tutorial with examples

NEXT READ Hibernate one to one example with annotation code
Sanmple Web Application with Hibernate Tutorial with examples
Follow us on social media to get latest tutorials, tips and tricks on Hibernate.

Please share us on social media if you like the tutorial.



Hibernate Application With Annotation Tutorial with Examples

The hibernate application can be created with annotation. There are many annotations that can be used to create hibernate application such as @Entity, @Id, @Table etc.

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.

Example to create the hibernate application with Annotation

Creating Database

Before we start lets create a simple database and table to apply hibernate operations on. Copy and Paste the following sql query in your query editor and execute.
CREATE table STUDENT (ID bigint identity,
rollno varchar(20),
firstname varchar(50),
lastname varchar(50),
course varchar(50),
address varchar(100))


NOTE : Above script is written for SQL Server, you can change accordingly for different DB.

Adding Hibernate Jars

Download latest Hibernate jars from here http://hibernate.org/ and add to your classpath.

Add hibernate.cfg.xml

It is a configuration file, containing informations about the database and mapping file.

put this file under root folder.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
        <property name="hibernate.connection.password">yourdbpassword</property>
        <property name="hibernate.connection.url">jdbc:jtds:sqlserver://localhost:1433/yourdbname</property>
        <property name="hibernate.connection.username">yourdbusername</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
     <property name="connection.pool_size">1</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.tutorialsdesk.hibernate.bean.Student"/>
        
    </session-factory>
</hibernate-configuration>


Adding Hibernate Utils class

This is a simple java class with a static method, we will use this class to get a session instance of hibernate session factory class.
package com.tutorialsdesk.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration; 

 
public class HibernateUtil {
 
 private static final SessionFactory sessionFactory = buildSessionFactory();

  private static SessionFactory buildSessionFactory() {
   try {
    return new AnnotationConfiguration().configure().buildSessionFactory(); 
   } catch (Throwable ex) {
    System.err.println("Initial SessionFactory creation failed." + ex);
    throw new ExceptionInInitializerError(ex);
   }
  }

  public static SessionFactory getSessionFactory() {
   return sessionFactory;
  }

  public static void shutdown() {
   getSessionFactory().close();
  }


}


Adding bean class file

This is a simple pojo consisting of an Student object, we will map this class to relational database using hibernate utilities.

@Entity annotation marks this class as an entity.

@Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name bydefault.

@Id annotation marks the identifier for this entity.

@Column annotation specifies the details of the column for this property or field. If @Column annotation is not specified, property name will be used as the column name bydefault.

package com.tutorialsdesk.hibernate.bean;

import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
import javax.persistence.Table;    
@Entity 
@Table(name="STUDENT") 

public class Student {

 @Id    
 @GeneratedValue   
 private int id;
 
 @Column(name="rollno")   
 private String rollno;
 
 @Column(name="firstname")   
 private String firstname;
 
 @Column(name="lastname")     
 private String lastname;
 
 @Column(name="course")   
 private String course;
 
 @Column(name="address")   
 private String address;
 
 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getRollno() {
  return rollno;
 }

 public void setRollno(String rollno) {
  this.rollno = rollno;
 }

 public String getFirstname() {
  return firstname;
 }

 public void setFirstname(String firstname) {
  this.firstname = firstname;
 }

 public String getLastname() {
  return lastname;
 }

 public void setLastname(String lastname) {
  this.lastname = lastname;
 }

 public String getCourse() {
  return course;
 }

 public void setCourse(String course) {
  this.course = course;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }


 
}


Implementation class code

This is simple java class containing main method to start execution, see the implementation to identify hibernate working in create, retrieve, update and delete operations.
package com.tutorialsdesk.hibernate;

import java.util.ArrayList;
import org.hibernate.*;
import org.hibernate.cfg.*;
import com.tutorialsdesk.hibernate.bean.Student;

public class AnnotationTest {
public static void main(String[] args) {
 Session session=new AnnotationConfiguration()
         .configure().buildSessionFactory().openSession();
 
 Transaction t=session.beginTransaction();
 AnnotationTest test=new AnnotationTest();
 Student s1=new Student();
 s1.setRollno("2014CS001");
 s1.setFirstname("Ankit");
 s1.setLastname("Yadav");
 s1.setCourse("MCA");
 s1.setAddress("Gomati Nagar, Lucknow");
 
 Student s2=new Student();
 s2.setRollno("2014CS002");
 s2.setFirstname("Rahul");
 s2.setLastname("Verma");
 s2.setCourse("B.Tech");
 s2.setAddress("Niti Khand, Ghaziabad");
 
 test.saveUser(s1);
 test.saveUser(s2);
 
 s2.setCourse("M.Tech");
 test.updateUser(s2);
 
 test.deleteUser(s1);
 
 test.getUser();
 System.out.println("successfully saved");
}
public void saveUser(Student student) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   session.save(student);

   session.getTransaction().commit();
  }

  public void updateUser(Student student) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   session.merge(student);

   session.getTransaction().commit();
  }

  public void deleteUser(Student student) {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   session.delete(student);

   session.getTransaction().commit();
  }

  public void getUser() {
   Session session = HibernateUtil.getSessionFactory().openSession();
   session.beginTransaction();

   ArrayList<Student> list = (ArrayList<Student>) session.createQuery("from Student").list();
   if (list != null) {
    for (int i = 0; i < list.size(); i++) {
     System.out.println("User ID : " + list.get(i).getId());
     System.out.println("User First Name : "+ list.get(i).getFirstname());
     System.out.println("User Last Name : "+ list.get(i).getLastname());
     System.out.println("User Roll No : " + list.get(i).getRollno());
     System.out.println("User Address : " + list.get(i).getCourse());
    
   }
   }
   session.getTransaction().commit();
  }

}


NEXT READ Example to create web application using hibernate

Hibernate Application With Annotation Tutorial with Examples
Follow us on social media to get latest tutorials, tips and tricks on Hibernate.

Please share us on social media if you like the tutorial.

Advantage And Disadvantages Of Hibernate

Hibernate is an ORM tool that automatically maps your domain object to the relational database. It helps to developers to quickly write database access program and become productive. But we will see the advantages and disadvantages of Hibernate ORM tool.

Java developers of all over the world is mostly using Hibernate or JPA (with Hibernate) for developing enterprise web applications. There are lots of material and tutorials on Hibernate on the web. As a developer if you are stuck some where in your programming, you can easily find the solution of your problem on the web.

Advantages of Hibernate

  • Hibernate is better then plain JDBC: You can use Hibernate which generates the SQL on the fly and then automatically executes the necessary SQL statements. This saves a lot of development and debugging time of the developer. Writing JDBC statement, setting the parameters, executing query and processing the result by hand is lot of work. Hibernate will save all tedious efforts.
  • Mapping of Domain object to relational database: Hibernate maps your domain object with the relational database. Now you can concentrate on your business logic rather than managing the data in database.
  • Layered architecture: Hibernate is layers architecture and you can use the components as per your application need.
  • JPA Provider: Hibernate can work as JPA provider in JPA based applications.
  • Standard ORM: Hibernate is standard ORM solutions and it also supports JPA.
  • Database Independent: Hibernate is database independent and you can use any database of your choice.
  • Caching Framework: There are many caching framework that works with Hibernate. You can use any one in your application to improve the performance of your application.

Disadvantages of Hibernate

  • Hibernate is little slower than pure JDBC, actually the reason being hibernate used to generate many SQL statements in run time, but i guess this is not the disadvantage
  • Not suitable for Batch processing, It advisable to use pure JDBC for batch processing.

NEXT READ Hibernate with Annotation

Advantage And Disadvantages Of Hibernates

Follow us on social media to get latest tutorials, tips and tricks on java.

Please share us on social media if you like the tutorial.

Hibernate Architecture


The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs. Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application.

There are 4 layers in hibernate architecture java application layer, hibernate framework layer, backhand api layer and database layer. Let's see the diagram of hibernate architecture:

Hibernate Architecture


Following is a detailed view of the Hibernate Application Architecture with few important core classes.


Hibernate Detailed Architecture

Hibernate framework uses many objects session factory, session, transaction etc. alongwith existing Java API such as JDBC (Java Database Connectivity), JTA (Java Transaction API) and JNDI (Java Naming Directory Interface).

Elements of Hibernate Architecture

For creating the first hibernate application, we must know the elements of Hibernate architecture. They are as follows:

Configuration

The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate. The Configuration object provides two keys components:
  • Database Connection: This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
  • Class Mapping Setup: This component creates the connection between the Java classes and database tables..

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.

The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects.

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.

The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.

Transaction

The transaction object specifies the atomic unit of work. It is optional. The org.hibernate.Transaction interface provides methods for transaction management.

This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.

ConnectionProvider

It is a factory of JDBC connections. It abstracts the application from DriverManager or DataSource.

Hibernate Connection management service provide efficient management of the database connections. Database connection is the most expensive part of interacting with the database as it requires a lot of resources of open and close the database connection.

TransactionFactory

It is a factory of Transaction.

Query

Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

Criteria

Criteria object are used to create and execute object oriented criteria queries to retrieve objects.

Hibernate provides a lot of flexibility in use. It is called "Lite" architecture when we only uses the object relational mapping component. While in "Full Cream" architecture all the three component Object Relational mapping, Connection Management and Transaction Management) are used.

NEXT READ Main Advantage And Disadvantages Of Hibernates

Follow us on social media to get latest tutorials, tips and tricks on java.

Please share us on social media if you like the tutorial.

Hibernate Intoduction and Overview


What is Hibernate

Hibernate is an open source object/relational mapping tool for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework.

Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.

It's create a “virtual object database” that can be used from within the programming language.

Hibernate is a persistence framework which is used to persist data from Java environment to database. Persistence is a process of storing the data to some permanent medium and retrieving it back at any point of time even after the application that had created the data ended.

Hibernate Intoduction and Overview

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

Features of Hibernate

  • Transparent persistence without byte code processing
  • Object-oriented query language
  • Object / Relational mappings
  • Automatic primary key generation
  • Object/Relational mapping definition
  • HDLCA (Hibernate Dual-Layer Cache Architecture)
  • High performance
  • J2EE integration

Advantages of Hibernate

  • 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 Database or in any table then the only need to change XML file properties.
  • Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects.
  • Hibernate does not require an application server to operate.
  • Manipulates Complex associations of objects of your database.
  • Minimize database access with smart fetching strategies.
  • Provides Simple querying of data.
Hibernate is Free Software. The LGPL license is sufficiently flexible to allow the use of Hibernate in both open source and commercial projects (see the LicenseFAQ for details). Hibernate is available for download at http://www.hibernate.org/.

NEXT READ Hibernate Architecture

Follow us on social media to get latest tutorials, tips and tricks on java.

Please share us on social media if you like the tutorial.
Hibernate Intoduction and Overview

Object-Relational Mapping (ORM) Tutorial

What is ORM

ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages such as Java.

Using an Object Relational Mapping library improves the application development process and runtime handling in many aspects. To handle the communication between the Object Domain model (Classes/Objects) and Relational Model (Table/Records), we would be wasting a lot of time in writing boiler plate template code. To ensure a seamless communication with robust implementation and good performance, it is better to embrace an already available ORM like Hibernate.

ORM is a programming method to map the objects in java with the relational entities in the database. In this,entities/classes refers to table in database,instance of classes refers to rows and attributes of instances of classes refers to column of table in database. This provides solutions to the problems arise while developing persistence applications using traditional JDBC method. This also reduces the code that needs to be written.

Why Object Relational Mapping (ORM)?

When we work with an object-oriented systems, there's a mismatch between the object model and the relational database. RDBMSs represent data in a tabular format whereas object-oriented languages, such as Java represent it as an interconnected graph of objects.

Loading and storing objects in a relational database exposes us to the following mismatch problems.
  • Granularity Sometimes you will have an object model which has more classes than the number of corresponding tables in the database.
  • Inheritance RDBMSs do not define anything similar to Inheritance which is a natural paradigm in object-oriented programming languages.
  • Identity A RDBMS defines exactly one notion of 'sameness': the primary key. Java, however, defines both object identity (a==b) and object equality (a.equals(b)).
  • Associations Object-oriented languages represent associations using object references where as am RDBMS represents an association as a foreign key column.
  • Navigation The ways you access objects in Java and in a RDBMS are fundamentally different.
The Object-Relational Mapping (ORM) is the solution to handle all the above impedance mismatches.

Advantages of ORM

An ORM system has following advantages over plain JDBC :
  • Improved productivity
    • High-level object-oriented API
    • Less Java code to write
    • No SQL to write
  • Improved performance
    • Sophisticated caching
    • Lazy loading
    • Eager loading
  • Improved maintainability
    • A lot less code to write
  • Improved portability
    • ORM framework generates database-specific SQL for you

Comparison of ORM with JDBC

Compared to traditional techniques of exchange between an object-oriented language and a relational database, ORM often reduces the amount of code that needs to be written.

Disadvantages of ORM tools generally stem from the high level of abstraction obscuring what is actually happening in the implementation code. Also, heavy reliance on ORM software has been cited as a major factor in producing poorly designed databases.

NEXT READ Hibernate Intoduction
Object-Relational Mapping (ORM) Tutorial

Follow us on social media to get latest tutorials, tips and tricks on java.

Please share us on social media if you like the tutorial.

Future and Callable in Java Tutorial with examples

Explaining Futures and Callable

Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.

Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util.concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.

Future provides cancel() method to cancel the associated Callable task. There is an overloaded version of get() method where we can specify the time to wait for the result, it’s useful to avoid current thread getting blocked for longer time. There are isDone() and isCancelled() methods to find out the current status of associated Callable task.

The Callable object uses generics to define the type of object which is returned.

If you submit a Callable object to an Executor the framework returns an object of type java.util.concurrent.Future. This Future object can be used to check the status of a Callable and to retrieve the result from the Callable.

On the Executor you can use the method submit to submit a Callable and to get a future. To retrieve the result of the future use the get() method.

Here is a simple example of Callable task that returns the name of thread executing the task after one second. We are using Executor framework to execute 100 tasks in parallel and use Future to get the result of the submitted tasks.

package com.tutorialsdesk.threads.callable;

import java.util.concurrent.Callable;

public class MyCallable implements Callable<long> {
  @Override
  public Long call() throws Exception {
    long sum = 0;
    for (long i = 0; i <= 100; i++) {
      sum += i;
    }
    return sum;
  }

} 



package com.tutorialsdesk.threads.callable;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableFutures {
  private static final int NTHREDS = 10;

  public static void main(String[] args) {

    ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
    List<Future<Long>> list = new ArrayList<Future<Long>>();
    for (int i = 0; i < 20000; i++) {
      Callable<Long> worker = new MyCallable();
      Future<Long> submit = executor.submit(worker);
      list.add(submit);
    }
    long sum = 0;
    System.out.println(list.size());
    // now retrieve the result
    for (Future<Long> future : list) {
      try {
        sum += future.get();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      }
    }
    System.out.println(sum);
    executor.shutdown();
  }
} 



NEXT READ Thread Pool Executor in Java.
Future and Callable in Java Tutorial with examples

Hope we are able to explain you Importance of Future and Callable in Java, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

RejectedExecutionHandler Thread Pool Executor in Java Tutorial with examples

Explaining RejectedExecutionHandler

A task can be rejected as well. We need to have something in place to resolve this situation because no one would like to miss any single job in his application.

RejectedExecutionHandler is a handler for tasks that cannot be executed by a ThreadPoolExecutor.

Executors class provide simple implementation of ExecutorService using ThreadPoolExecutor but ThreadPoolExecutor provides much more feature than that. We can specify the number of threads that will be alive when we create ThreadPoolExecutor instance and we can limit the size of thread pool and create our own RejectedExecutionHandler implementation to handle the jobs that can’t fit in the worker queue.

Here is our custom implementation of RejectedExecutionHandler interface.
package com.tutorialsdesk.threads;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor; 
public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {   
 @Override   
 public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {  
  System.out.println(r.toString() + " is rejected");  
  }  
 } 




ThreadPoolExecutor provides several methods using which we can find out the current state of executor, pool size, active thread count and task count. So I have a monitor thread that will print the executor information at certain time interval.
package com.tutorialsdesk.threads;

import java.util.concurrent.ThreadPoolExecutor; 
public class MyMonitorThread implements Runnable {   
 private ThreadPoolExecutor executor;        
 private int seconds;        
 private boolean run=true;     
 public MyMonitorThread(ThreadPoolExecutor executor, int delay)     {  
  this.executor = executor;     
  this.seconds=delay;    
  }          
 public void shutdown(){       
  this.run=false;    
  }      
 @Override   
 public void run()     {  
  while(run){   
   System.out.println(    
     String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s",  
       this.executor.getPoolSize(),      
       this.executor.getCorePoolSize(),   
       this.executor.getActiveCount(),   
       this.executor.getCompletedTaskCount(),  
       this.executor.getTaskCount(),          
       this.executor.isShutdown(),               
       this.executor.isTerminated()));         
   try {                     Thread.sleep(seconds*1000);   
   } catch (InterruptedException e) {   
    e.printStackTrace();              
    }      
   }                 
  } 
 } 




Here is the thread pool implementation example using ThreadPoolExecutor.
package com.tutorialsdesk.threads;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors; 
import java.util.concurrent.ThreadFactory; 
import java.util.concurrent.ThreadPoolExecutor; 
import java.util.concurrent.TimeUnit; 
public class WorkerPool {      
 public static void main(String args[]) throws InterruptedException{   
  //RejectedExecutionHandler implementation      
  RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();         
  //Get the ThreadFactory implementation to use       
  ThreadFactory threadFactory = Executors.defaultThreadFactory();  
  //creating the ThreadPoolExecutor        
  ThreadPoolExecutor executorPool = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), threadFactory, rejectionHandler);        
  //start the monitoring thread         
  MyMonitorThread monitor = new MyMonitorThread(executorPool, 3);    
  Thread monitorThread = new Thread(monitor);      
  monitorThread.start();       
  //submit work to the thread pool      
  for(int i=0; i<10; i++){           
   executorPool.execute(new MyRunnable("cmd"+i));       
   }                   Thread.sleep(30000);     
   //shut down the pool         
   executorPool.shutdown();       
   //shut down the monitor thread    
   Thread.sleep(5000);         
   monitor.shutdown();          
   } 
 
 }


Notice that while initializing the ThreadPoolExecutor, we are keeping initial pool size as 2, maximum pool size to 4 and work queue size as 2. So if there are 4 running tasks and more tasks are submitted, the work queue will hold only 2 of them and rest of them will be handled by RejectedExecutionHandlerImpl.

Here is the output of above program that confirms above statement.
Command 6 is rejected
Command 7 is rejected
Command 8 is rejected
Command 9 is rejected
pool-1-thread-1 Start. Thread from Pool = Command 0
pool-1-thread-3 Start. Thread from Pool = Command 4
[monitor] [4/2] Active: 4, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
pool-1-thread-2 Start. Thread from Pool = Command 1
pool-1-thread-4 Start. Thread from Pool = Command 5
pool-1-thread-1 End.
pool-1-thread-1 Start. Thread from Pool = Command 2
pool-1-thread-3 End.
pool-1-thread-3 Start. Thread from Pool = Command 3
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-3 End.
pool-1-thread-1 End.
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true


Notice the change in active, completed and total completed task count of the executor. We can invoke shutdown() method to finish execution of all the submitted tasks and terminate the thread pool.

If you want to schedule a task to run with delay or periodically then you can use ScheduledThreadPoolExecutor class.

NEXT READ Future and Callable in Java.

RejectedExecutionHandler Thread Pool Executor in Java Tutorial with examples
Hope we are able to explain you Importance of RejectedExecutionHandler Thread Pool Executor in Java, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Thread Pool Executor in Java Tutorial with examples

Thread pools in Java

A thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed.

The basic idea is as follows:
  • whenever we want a job performing, instead of creating a thread for it directly, we put it on to a queue;
  • a (fairly) fixed set of long-running threads each sit in a loop pulling jobs off the queue and running them.
In java A thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue.
  • a thread pool implementation is provided in the form of the ThreadPoolExecutor class, part of the Java concurrency framework introduced in Java 5;
  • you can plug in different implementations of BlockingQueue in order to specifiy different queue behaviour such as queue bounds or priority ordering
A thread pool is represented by an instance of the class ExecutorService. With an ExecutorService, you can submit task that will be completed in the future. Here are the type of thread pools you can create with the Executors class :
  • Single Thread Executor : A thread pool with only one thread. So all the submitted tasks will be executed sequentially. Method : Executors.newSingleThreadExecutor()
  • Cached Thread Pool : A thread pool that creates as many threads it needs to execute the task in parrallel. The old available threads will be reused for the new tasks. If a thread is not used during 60 seconds, it will be terminated and removed from the pool. Method : Executors.newCachedThreadPool()
  • Fixed Thread Pool : A thread pool with a fixed number of threads. If a thread is not available for the task, the task is put in queue waiting for an other task to ends. Method : Executors.newFixedThreadPool()
  • Scheduled Thread Pool : A thread pool made to schedule future task. Method : Executors.newScheduledThreadPool()
  • Single Thread Scheduled Pool : A thread pool with only one thread to schedule future task. Method : Executors.newSingleThreadScheduledExecutor()
The Executor framework provides example implementation of the java.util.concurrent.Executor interface, e.g. Executors.newFixedThreadPool(int n) which will create n worker threads. The ExecutorService adds life cycle methods to the Executor, which allows to shutdown the Executor and to wait for termination.

Let’s write a simple program to explain it’s working.

First we need to have a Runnable class.
package com.tutorialsdesk.threads;

public class MyRunnable implements Runnable {
    
    private String command;
    
    public MyRunnable(String s){
        this.command=s;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" Start. Thread from Pool = "+command);
        processCommand();
        System.out.println(Thread.currentThread().getName()+" End.");
    }

    private void processCommand() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString(){
        return this.command;
    }
}




Now you run your runnables with the executor framework.
package com.tutorialsdesk.threads;

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
public class SimpleThreadPool {       
 public static void main(String[] args) {      
  ExecutorService executor = Executors.newFixedThreadPool(3);     
  for (int i = 0; i < 10; i++) {        
   Runnable myRunnable = new MyRunnable("" + i);      
   executor.execute(myRunnable);          
   }      
  executor.shutdown();    
  while (!executor.isTerminated()) {     
   
  }        
  System.out.println("Finished all threads");  
  } 
 } 




In above program, we are creating fixed size thread pool of 5 worker threads. Then we are submitting 10 jobs to this pool, since the pool size is 5, it will start working on 5 jobs and other jobs will be in wait state, as soon as one of the job is finished, another job from the wait queue will be picked up by worker thread and get’s executed. Here is the output of the above program.
pool-1-thread-1 Start. Thread from Pool = 0
pool-1-thread-3 Start. Thread from Pool = 2
pool-1-thread-2 Start. Thread from Pool = 1
pool-1-thread-1 End.
pool-1-thread-1 Start. Thread from Pool = 3
pool-1-thread-3 End.
pool-1-thread-3 Start. Thread from Pool = 4
pool-1-thread-2 End.
pool-1-thread-2 Start. Thread from Pool = 5
pool-1-thread-1 End.
pool-1-thread-1 Start. Thread from Pool = 6
pool-1-thread-3 End.
pool-1-thread-3 Start. Thread from Pool = 7
pool-1-thread-2 End.
pool-1-thread-2 Start. Thread from Pool = 8
pool-1-thread-1 End.
pool-1-thread-1 Start. Thread from Pool = 9
pool-1-thread-3 End.
pool-1-thread-2 End.
pool-1-thread-1 End.
Finished all threads


The output confirms that there are five threads in the pool named from “pool-1-thread-1? to “pool-1-thread-5? and they are responsible to execute the submitted tasks to the pool.

NEXT READ RejectedExecutionHandler Thread Pool Executor in Java.

Hope we are able to explain you Importance of Thread Pool Executor in Java, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.
Thread Pool Executor in Java Tutorial with examples

Why use @Override annotation in Java Tutorial with Examples

When we use @Override annotation to a method, it let compiler know that we are overriding it from super class. It is not mandatory to use @Override when you override a method. Incase you are using @Override annotation, and the method signature is not found at super class will results compilation error.

@Override annotation was added in JDK 1.5 and it is used to instruct compiler that method annotated with @Override is an overridden method from super class or interface. Though it may look trivial @Override is particularly useful while overriding methods which accept Object as parameter just like equals, compareTo or compare() method of Comparator interface.

One of the major problem with @Override annotation on JDK 1.5 was that it can only be used to in conjunction with super class i.e. compiler throws error if you use @Override annotation with interface method. From Java 6 onwards you can use @Override annotation while implementing interface method as well. This provides robust compile time checking of overriding.

@Override annotation example

Let’s see how we normally override a method in java.
We have a superclass Vehicle.java as below.
package com.tutorialsdesk.annotations;

public class Car extends Vehicle{
 public void make(String make){
  System.out.println("Car Make : "+make); 
 }
}


Now we will create a subclass Car overriding Vehicle make method.
package com.tutorialsdesk.annotations;

public class Car extends Vehicle{
 public void make(String make){
  System.out.println("Car Make : "+make); 
 }
}


Now let’s create a TestAnnotation class to check how overriding works in java.
package com.tutorialsdesk.annotations;

public class TestAnnotation {

 public static void main(String[] args) {         
  Vehicle vehicle = new Car();         
  vehicle.make("Honda");     
  } 
}


Output of the above program is:
Car Make : Honda


Here “vehicle” is of type Vehicle but at runtime it’s object of Car, so when we invoke it’s make(String str) method, it looks for the method in Car and hence the output. Now let’s change the Vehicle make method like below.
package com.tutorialsdesk.annotations;

public class Vehicle {
 public void make(Object make){
  System.out.println("Vegicle Make : "+make); 
 }
}


You will notice that compiler won’t throw any warnings/errors and now if you run the TestAnnotation program output will be;
Vegicle Make : Honda


The reason is that Vehicle make(Object str) method is not overridden anymore by Car and hence it’s invoking Vehicle implementation. Car is overloading the make() method in this case.

If you will use the @Override annotation in Car class
package com.tutorialsdesk.annotations;

public class Car extends Vehicle{
 @Override
 public void make(String make){
  System.out.println("Car Make : "+make); 
 }
}


you will get following compile time error message:
The method make(String) of type Car must override or implement a supertype method


It’s clear that using Override annotation will make sure any Superclass changes in method signature will result in a warning and you will have to do necessary changes to make sure the classes work as expected.

It’s better to resolve potential issues at Compile time than rumtime. So always use @Override annotation whenever you are trying to override a superclass method.

When to use @Override annotation

  1. When a class method is overriding a super-class method.
  2. When a class method is implementing an interface method.
  3. When an interface method respecifying a super-interface method.
Only place, where you don't want to use @Override is when the parent method is @Deprecated.

you can read here in detail about Annotations in java.

NEXT READ Java Custom Annotation and Parsing using Reflection.

Why use @Override annotation in Java Tutorial with Examples
Hope we are able to explain you Importance of Java @Override Annotation, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Write to a CSV file in java Tutorial with examples

A csv file is a simple text file containing text data, separated with a white space or a comma.

How to Write to a csv file in Java

we just need to write values seperated by comma to the file line by line. Below is the java code to write values to csv file.
import java.io.FileWriter;
import java.io.IOException;
 
public class WriteCSV
{
   public void generateCsvFile(String outPutFile)
   {
        try
        {
            FileWriter writer = new FileWriter(outPutFile);
            writer.append("BNP_BOND_1234");
            writer.append(",");
            writer.append("BNP Flexi Bond");
            writer.append(",");
            writer.append("50");
            writer.append("\n");
            
            writer.append("FIS_MF_4567");
            writer.append(",");
            writer.append("FIS Super Saver Fund");
            writer.append(",");
            writer.append("110");
            writer.append("\n");
            
            writer.append("BIRLA_MF_2789");
            writer.append(",");
            writer.append("BIRLA Mutual Fund");
            writer.append(",");
            writer.append("180");
            writer.append("\n");
            //generate whatever data you want 
            writer.flush();
            writer.close();
        }
        catch(IOException e)
        {
             e.printStackTrace();
        } 
    }
   
   public static void main(String args[]){
           String outPutFile = "D:/Assignment/ProductList.csv";
           WriteCSV writer=new WriteCSV();
           writer.generateCsvFile(outPutFile);
   }
}

Output

Above program will create a csv file with following values
BNP_BOND_1234,BNP Flexi Bond,50

FIS_MF_4567,FIS Super Saver Fund,110

BIRLA_MF_2789,BIRLA Mutual Fund,180

NEXT READ Read and Parse a CSV file in java.
Write to a CSV file in java Tutorial with examples

Follow us on social media to get latest tutorials, tips and tricks on java.

Please share us on social media if you like the tutorial.

Read and Parse a CSV file in java Tutorial with examples

A csv file is a simple text file containing text data, separated with a white space or a comma, to read a csv file in java we just need to read the file line by line and separate the values splitting by comma(',') or white-space(' ') accordingly.

Sample CSV file to read containing data separated by comma(',')

create a file in notepad with following data and save it as ProductQuantity.csv extension.
Product Code,Product Name,Quantity
BNP_BOND_1234,BNP Flexi Bond,50
FIS_MF_4567,FIS Super Saver Fund,110
BIRLA_MF_2789,BIRLA Mutual Fund,180
REL_BFWD_5678,REL Equity Bond,40

How to read and parse a csv file in Java

We have taken a sample csv file here that contains data separated by comma(','), we just need to read the file line by line and split the values by comma(',') to print values on console. Below is the java code to read values from csv file.
package com.tutorialsdesk.csv;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadCSVFile {
        public void readFile(String csvFileToRead) {
                BufferedReader br = null;
                String line = "";
                String splitBy = ",";
                try {
                        br = new BufferedReader(new FileReader(csvFileToRead));
                        while ((line = br.readLine()) != null) {
                                String[] products = line.split(splitBy);
                                System.out.println("Products [Code= " + products[0] + " , Desc="+ products[1] +
" , Quantity=" + products[2]  + "]");
                        }
                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        if (br != null) {
                                try {
                                        br.close();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                }
 }
 
 public static void main(String args[]){
         String csvFileToRead = "D:/Assignment/ProductQuantity.csv";
         ReadCSVFile reader = new ReadCSVFile();
         reader.readFile(csvFileToRead);
 }
}

Output

Below is the output of above program
Products [Code= Product Code , Desc=Product Name , Quantity=Quantity]
Products [Code= BNP_BOND_1234 , Desc=BNP Flexi Bond , Quantity=50]
Products [Code= FIS_MF_4567 , Desc=FIS Super Saver Fund , Quantity=110]
Products [Code= BIRLA_MF_2789 , Desc=BIRLA Mutual Fund , Quantity=180]
Products [Code= REL_BFWD_5678 , Desc=REL Equity Bond , Quantity=40]

NEXT READ Write to a CSV file in java.
Read and Parse a CSV file in java Tutorial with examples

Follow us on social media to get latest tutorials, tips and tricks on java.

Please share us on social media if you like the tutorial.

How To Iterate Through Map or Hashmap in Java

Iterating over any of the Map implementation(Hashmap, TreeMap etc) is not very straight forward compared to other collections as it is two steps process. There are different ways you can iterate over Map, but in this example we will see how to iterate using advanced for loop and using the Iterator object. We will use following three different ways to traverse.
  • Using Iterator interface
  • Using entrySet() and for loop
  • Using keyset() and for loop
If you want to remove the elements from Hashmap while iterating, then First option suitable for this kind of requirements. The last two will through java.util.ConcurrentModificationException if you remove while iterating.

Java Program to Iterate HashMap

package com.tutorialsdesk.collection;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapIterator {

public static void main(String[] args) {

 Map<String, Integer> map = new HashMap<String, Integer>();

 map.put("ONE", 1);
 map.put("TWO", 2);
 map.put("THREE", 3);
 map.put("FOUR", 4);
 map.put("FIVE", 5);
 System.out.println("Using Iterator");   
 Set<String> setOfKeys = map.keySet();
 Iterator<String> iterator = setOfKeys.iterator();
 while (iterator.hasNext()) {
        String key = (String) iterator.next();
        Integer value = map.get(key);
        System.out.println(key+" :: "+ value);
        //iterator.remove(); 
        //You can remove elements while iterating.   
 }

System.out.println("Using EntrySet");         
for(Map.Entry<String, Integer> maps : map.entrySet()){ 
        System.out.println(maps.getKey() +" :: "+ maps.getValue()); 
        //if you uncomment below code, it will throw
java.util.ConcurrentModificationException             
        //map.remove("FIVE"); 
}

System.out.println("Using KeySet");        
for(String key: map.keySet()){            
        System.out.println(key  +" :: "+ map.get(key));
        //if you uncomment below code, it will throw
java.util.ConcurrentModificationException             
        //map.remove("FIVE"); 
}

 }

 }

Output

Below is the output of above program
Using Iterator
ONE :: 1
TWO :: 2
THREE :: 3
FOUR :: 4
FIVE :: 5
Using EntrySet
ONE :: 1
TWO :: 2
THREE :: 3
FOUR :: 4
FIVE :: 5
Using KeySet
ONE :: 1
TWO :: 2
THREE :: 3
FOUR :: 4
FIVE :: 5

NEXT READ Read and Parse a CSV file in java.
How To Iterate Through Map or Hashmap in Java

Follow us on social media to get latest tutorials, tips and tricks on java.

Please share us on social media if you like the tutorial.

Java Custom Annotation and Parsing using Reflection Tutorial with examples

Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

Java annotations were added to Java from Java 5 and now it’s heavily used in Java frameworks like Hibernate, Jersey, Spring.

Before annotations, program metadata was available through java comments or by javadoc but annotation offers more than that. It not only contains the metadata but it can made it available to runtime and annotation parsers can use it to determine the process flow. For example, in Jersey webservice we add PATH annotation with URI string to a method and at runtime jersey parses it to determine the method to invoke for given URI pattern.

Read here more about annotations in java.

Creating Custom Annotations in Java

Creating custom annotation is similar to writing an interface, except that it interface keyword is prefixed with @ symbol. We can declare methods in annotation. Let’s see annotation example.
package com.tutorialsdesk.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
 String author() default "TutorialsDesk";
 int version() default 1;
}



Here , the RetentionPolicy.RUNTIME will determine whether the annotation will be present at run time or not.To test the annotation and get the values , let's create a test class
package com.tutorialsdesk.annotations;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class CustomAnnotationTest {
 
 @CustomAnnotation(author="TutorialsDesk",version=2)
 public void annotationTest()
 {
  
 }
 
 
 public static void main(String[] args) {
  Method[] methods = CustomAnnotationTest.class.getDeclaredMethods();
  
  for(Method m : methods)
  {
   for(Annotation a : m.getAnnotations())
   {
    if ( a instanceof CustomAnnotation)
    {
     CustomAnnotation ann = (CustomAnnotation)a;
     System.out.println(ann.author());
     System.out.println(ann.version());
    }
   }
  }
  
  
  
 }

}


Here annotation is on method level , we can access the annotation element values using reflection on method.If the do not specify RetentionPolicy as RUNTIME , the jvm will ignore this annotation and we will not be able to access this annotation.

Points to remember while writing Custom Annotations in Java

  • Annotation methods can’t have parameters.
  • Annotation methods return types are limited to primitives, String, Enums, Annotation or array of these.
  • Annotation methods can have default values.
  • Annotations can have meta annotations attached to them. Meta annotations are used to provide information about the annotation.
you can read here in detail about Java Built-in Annotations.

NEXT READ Why should we use @override Annotations in Java

Java Custom Annotation and Parsing using Reflection Tutorial with examples
Hope we are able to explain you Java Custom Annotation and Parsing using Reflection, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.

Java Annotations Tutorial with examples

Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

Java annotations were added to Java from Java 5.

Uses of Annotations in Java

Annotations are far more powerful than java comments and javadoc comments. One main difference with annotation is it can be carried over to runtime and the other two stops with compilation level. Annotations are not only comments, it brings in new possibilities in terms of automated processing.

Java annotations are typically used for the following purposes:
  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
  • Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
  • Runtime processing — Some annotations are available to be examined at runtime.

Annotations Basics

In its simplest form, an annotation looks like the following:
@Entity


The at sign character (@) indicates to the compiler that what follows is an annotation. In the following example, the annotation's name is Override:
@Override
void myMethod() { ... }


Annotation Elements

The annotation can include elements, which can be named or unnamed, and there are values for those elements:
@Author(
   name = "Benjamin Franklin",
   date = "3/27/2003"
)
class MyClass() { ... }


or
@SuppressWarnings(value = "unchecked")
void myMethod() { ... }


If there is just one element named value, then the name can be omitted, as in:
@SuppressWarnings("unchecked")
void myMethod() { ... }


If the annotation has no elements, then the parentheses can be omitted, as shown in the previous @Override example

Repeating annotation

It is also possible to use multiple annotations on the same declaration:
@Author(name = "Jane Doe")
@EBook
class MyClass { ... }

If the annotations have the same type, then this is called a repeating annotation:
@Author(name = "Jane Doe")
@Author(name = "John Smith")
class MyClass { ... }


Repeating annotations are supported as of the Java 8 release.

Built-in annotations

Java defines a set of annotations that are built into the language.

Annotations applied to Java code:

  • @Override - Checks that the method is an override. Causes a compile error if the method is not found in one of the parent classes or implemented interfaces.
  • public class MySuperClass {
    
        public void doTheThing() {
            System.out.println("Do the thing");
        }
    }
    
    
    public class MySubClass extends MySuperClass{
    
        @Override
        public void doTheThing() {
            System.out.println("Do it differently");
        }
    }
    
    
    
  • @Deprecated - Marks the method as obsolete. Causes a compile warning if the method is used.
  • public interface House { 
        /**
         * @deprecated use of open 
         * is discouraged, use
         * openFrontDoor or 
         * openBackDoor instead.
         */
        @Deprecated
        public void open(); 
        public void openFrontDoor();
        public void openBackDoor();
    }
    
    
    
  • @SuppressWarnings - Instructs the compiler to suppress the compile time warnings specified in the annotation parameters.
  • @SuppressWarnings
    public void methodWithWarning() {
    
    
    }
    
    
    
  • @SafeVarargs - Suppress warnings for all callers of a method or constructor with a generics varargs parameter, since Java 7.
  • @FunctionalInterface - Specifies that the type declaration is intended to be a functional interface, since Java 8.

Annotations applied to other annotations:

  • @Retention - Specifies how the marked annotation is stored—Whether in code only, compiled into the class, or available at runtime through reflection.
    • RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler.
    • RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
    • RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.
  • @Documented - Marks another annotation for inclusion in the documentation.
  • @Target - Marks another annotation to restrict what kind of Java elements the annotation may be applied to.
    • ElementType.ANNOTATION_TYPE can be applied to an annotation type.
    • ElementType.CONSTRUCTOR can be applied to a constructor.
    • ElementType.FIELD can be applied to a field or property.
    • ElementType.LOCAL_VARIABLE can be applied to a local variable.
    • ElementType.METHOD can be applied to a method-level annotation.
    • ElementType.PACKAGE can be applied to a package declaration.
    • ElementType.PARAMETER can be applied to the parameters of a method.
    • ElementType.TYPE can be applied to any element of a class.
  • @Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses).
  • @Repeatable - Specifies that the annotation can be applied more than once to the same declaration.

Type Annotations and Pluggable Type Systems

Before the Java SE 8 release, annotations could only be applied to declarations. As of the Java SE 8 release, annotations can also be applied to any type use. This means that annotations can be used anywhere you use a type. A few examples of where types are used are class instance creation expressions (new), casts, implements clauses, and throws clauses.

Type annotations were created to support improved analysis of Java programs way of ensuring stronger type checking. The Java SE 8 release does not provide a type checking framework, but it allows you to write (or download) a type checking framework that is implemented as one or more pluggable modules that are used in conjunction with the Java compiler.

For example, you want to ensure that a particular variable in your program is never assigned to null; you want to avoid triggering a NullPointerException. You can write a custom plug-in to check for this. You would then modify your code to annotate that particular variable, indicating that it is never assigned to null. The variable declaration might look like this:

@NonNull String str;

When you compile the code, including the NonNull module at the command line, the compiler prints a warning if it detects a potential problem, allowing you to modify the code to avoid the error. After you correct the code to remove all warnings, this particular error will not occur when the program runs.

Defining own annotations

It is possible to create your own annotations. Annotations are defined in their own file, just like a Java class or interface. Here is an example:
@interface ClassPreamble {
   String author();
   String date();
   int currentRevision() default 1;
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   // Note use of array
   String[] reviewers();
}



The annotation type definition looks similar to an interface definition where the keyword interface is preceded by the at sign (@) (@ = AT, as in annotation type). Annotation types are a form of interface, which will be covered in a later lesson. For the moment, you do not need to understand interfaces.

The body of the previous annotation definition contains annotation type element declarations, which look a lot like methods. Note that they can define optional default values.

After the annotation type is defined, you can use annotations of that type, with the values filled in, like this:

@ClassPreamble (
   author = "Tutorials Desk",
   date = "09/10/2014",
   currentRevision = 1,
   lastModified = "09/10/2014",
   lastModifiedBy = "Tutorials Desk",
   // Note array notation
   reviewers = {"Tutorials Desk", "Prakash"}
)
public class Generation3List extends Generation2List {

// class code goes here

}



To make the information in @ClassPreamble appear in Javadoc-generated documentation, you must annotate the @ClassPreamble definition with the @Documented annotation:
 

// import this to use @Documented
import java.lang.annotation.*;

@Documented
@interface ClassPreamble {

   // Annotation element definitions
   
}



Marker Annotations

We know what a marker interface is. Marker annotations are similar to marker interfaces, yes they don’t have methods / elements.
/**
 * Code annotated by this team is supreme and need
 * not be unit tested - just for fun!
 */
public @interface SuperTeam { }

@SuperTeam 
public static void readCSV(File inputFile) { }


In the above see how this annotation is used. It will look like one of the modifiers for this method and also note that the parenthesis () from annotation type is omitted. As there are no elements for this annotation, the parenthesis can be optionally omitted.

NEXT READ : Java Custom Annotations Example.

Java Annotations Tutorial with examples

Hope we are able to explain you Java Annotations, if you have any questions or suggestions please write to us using contact us form.(Second Menu from top left).

Please share us on social media if you like the tutorial.