Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Tuesday, January 27, 2015

No data type for node: org.hibernate.hql.internal.ast.tree.IdentNode \-[IDENT] IdentNode: 'e' {originalText=e}

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.IdentNode 
 \-[IDENT] IdentNode: 'e' {originalText=e}

HQL query:
Query query = session.createQuery("SELECT e FROM Employee");

Problem: 
In the above query, 'e' alias name is given in Employee table.

Solution: 
Query query = session.createQuery("SELECT e FROM Employee e");

Sunday, January 25, 2015

How to display all tables in different databases

In this article, we will see how to connect to the different databases(MySQL, Oracle, PostgreSQL, DB2) and how to display the all table names. 


MySQL

Connect to the database:
mysql [-u username] [-h hostname] database-name

To list all databases, in the MySQL prompt type:
show databases

Then choose the right database:
use <database-name>

List all tables in the database:
show tables

Describe a table:

desc <table-name>

Oracle

Connect to the database: 
connect username/password@database-name;

To list all tables owned by the current user, type:
select tablespace_name, table_name from user_tables;

To list all tables in a database:
select tablespace_name, table_name from dba_tables;

To list all tables accessible to the current user, type:
select tablespace_name, table_name from all_tables;

To describe a table:
desc <table_name>;

PostgreSQL

Connect to the database:
psql [-U username] [-h hostname] database-name

To list all databases, type either one of the following:
list

To list tables in a current database, type:
\dt

To describe a table, type:
\d <table-name>

DB2

Connect to the database:
db2 connect to <database-name>;

List all tables:
db2 list tables for all;

To list all tables in selected schema, use:
db2 list tables for schema <schema-name>;

To describe a table, type:
db2 describe table <table-schema.table-name>;
Happy coding...

Find duplicate elements in ArrayList

There are four ways is there to find duplicate element in arraylist.
  1. Using ArrayList contains method   
  2. Using HashSet
  3. Using HashMap
  4. Without using above
package com.varasofttech;

import java.util.*;


/**
* @author Ranga Reddy
* @date Jan 25, 2015
* @version 1.0
* @description : Displaying the all duplicate elements and how many times it found
*/


class Application {
public static void main(String args[]) {
List<String> names = getNames();
System.out.println("Displaying all names : "+ names);

String duplicateName = "Ranga";
System.out.println("\nFinding the name "+duplicateName +" how many times found");
System.out.println(duplicateName+" found in "+Collections.frequency(names,duplicateName)+" times.");

System.out.println("\nFinding the duplicate elements using ArrayList contains() method ");
List<String> tempNames = new ArrayList<String>();
for(String name : names) {
if(!tempNames.contains(name)) {
tempNames.add(name);
}
}
for(String name : tempNames) {
System.out.println(name+" found in "+ Collections.frequency(names, name) +" times");
}

System.out.println("\nFinding the duplicate elments using HashSet ");
Set<String> filteredSet = new HashSet<String>(names);
printSet(filteredSet,names);

System.out.println("\nFinding the duplicate elments using LinkedHashSet ");
Set<String> listToSet = new LinkedHashSet<String>(names);
printSet(listToSet,names);

System.out.println("\nFinding the duplicate elments using HashMap ");
Map<String,Integer> filteredMap = new HashMap<String,Integer>();
for(String name: names) {
Integer count = filteredMap.get(name);
filteredMap.put(name, (count == null)? 1: count + 1);
}
printMap(filteredMap);

System.out.println("\nFinding the duplicate elments using TreeMap ");
Map<String,Integer> filteredTreeMap = new TreeMap<String,Integer>();
for(String name: names) {
Integer count = filteredTreeMap.get(name);
filteredTreeMap.put(name, (count == null)? 1: count + 1);
}
printMap(filteredTreeMap);
}

private static void printSet(Set<String> filteredSet,List<String> names) {
for(String name : filteredSet) {
System.out.println(name+" found in "+ Collections.frequency(names, name) +" times");
}
}

private static void printMap(Map<String,Integer> filteredMap) {
for(String key: filteredMap.keySet()) {
System.out.println(key+" found in "+ filteredMap.get(key) +" times");
}
}

private static List<String> getNames() {
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Raja");
names.add("Vasu");
names.add("Reddy");
names.add("Manoj");
names.add("Raja");
names.add("Ranga");
names.add("Vasu");
names.add("Yasu");
names.add("Pavi");
names.add("Ranga");
return names;
}
}

Creating Custom Generator class in Hibernate

In this post, we are going to learn how to create custom generator class in hibernate.

Hibernate supports many built in generator classes like assigned, sequence, increment, identity, native etc. But some requirements these generator classes we can't use. For example while creating new Employee record, i want to insert employee id is Emp00001, Emp00002, etc like that. There is no built in generator classes support this type of primary key generated value. So we need to go for Custom generator classes.

In order to create our own generator class, we need to implement with the org.hibernate.id.IdentifierGenerator interface. This interface is having one method. So this method we need override.

package com.varasofttech.generator;

import org.hibernate.id.IdentifierGenerator;

public class MyGenerator implements IdentifierGenerator
{
@Override
public Serializable generate(SessionImplementor session, Object object)
{
// your logic comes here.
}

}

Tools & Technologies used in this article:
  1. JDK 1.6 or above
  2. Hibernate 4.3.6
  3. HSQL DB
  4. Eclipse Luna
Required Libraries:
  • antlr-2.7.7.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.5.Final.jar
  • hibernate-core-4.3.6.Final.jar
  • hibernate-jpa-2.1-api-1.0.0.Final.jar
  • jandex-1.1.0.Final.jar
  • javassist-3.18.1-GA.jar
  • jboss-logging-3.1.3.GA.jar
  • jboss-logging-annotations-1.2.0.Beta1.jar
  • jboss-transaction-api_1.2_spec-1.0.0.Final.jar
  • hsqldb-2.2.8.jar
Project Structure:

Step1: Creating the POJO or Model class: Employee.java
package com.varasofttech.pojo;

import java.io.Serializable;

/**
* @author Ranga Reddy
* @date Jan 25, 2015
* @version 1.0
* @description : Employee.java
*/


public class Employee implements Serializable {

private static final long serialVersionUID = -9001198124094210159L;

private String id; // identifier
private String name;
private int age;
private float salary;

// setters and getters
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age
+ ", salary=" + salary + "]";
}
}


Step2: Creating the Custom Generated Class: EmployeeNumberGenerator.java
package com.varasofttech.id;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;

/**
* @author Ranga Reddy
* @date Jan 25, 2015
* @version 1.0
* @description : EmployeeNumberGenerator.java
*/


public class EmployeeNumberGenerator implements IdentifierGenerator {

private String DEFAULT_SEQUENCE_NAME = "hibernate_sequence";

@Override
public Serializable generate(SessionImplementor sessionImpl, Object data)
throws HibernateException {
Serializable result = null;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
String prefix = "Emp";
connection = sessionImpl.connection();
statement = connection.createStatement();
try {
resultSet = statement.executeQuery("call next value for "+DEFAULT_SEQUENCE_NAME);
             } catch(Exception ex) {
// if sequence is not found then creating the sequence
statement = connection.createStatement();
statement.execute("CREATE SEQUENCE "+DEFAULT_SEQUENCE_NAME);
System.out.println("Sequece Created successfully. ");
resultSet = statement.executeQuery("call next value for "+DEFAULT_SEQUENCE_NAME);
}

if(resultSet.next()) {
int nextValue = resultSet.getInt(1);
String suffix = String.format("%05d", nextValue + 1);
result = prefix.concat(suffix);
System.out.println("Custom generated Sequence value : "+result);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}

Note: Getting the next value of Sequence value in different database is

Oracle: "SELECT "+sequenceName+".NEXTVAL FROM DUAL"
PostgreSQL: "SELECT  NEXTVAL('+sequenceName+"')  

Step3: Creating the Mapping File : employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="com.varasofttech.pojo.Employee" table="employees">
<id name="id" column="employeeId">
<generator class="com.varasofttech.id.EmployeeNumberGenerator"/>
</id>
<property name="name" column="e_name"></property>
<property name="age" column="e_age" />
<property name="salary" column="e_salary" />
</class>
</hibernate-mapping>

Step4: Creating the Configuration file : hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>

<!-- Database Settings -->
<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="hibernate.connection.url">jdbc:hsqldb:varasoftech</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>

<!-- Dialect class -->
<property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>

<!-- Hibernate specific -->
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.format_sql">true</property>

<mapping resource="Employee.hbm.xml"></mapping>

</session-factory>
</hibernate-configuration>

Step5: Creating the Hibernate Utility class : HibernateUtil.java
package com.varasofttech.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
/**
* @author Ranga Reddy
* @date Jan 25, 2015
* @version 1.0
* @description : HibernateUtil.java
*/

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

private static SessionFactory buildSessionFactory() {
try {

// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();

return configuration.buildSessionFactory(serviceRegistry);

} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static void closeSessionFactory() {
if(sessionFactory != null) {
sessionFactory.close();
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}


Step6: Creating the Client Application class : Application.java
package com.varasofttech.client;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.varasofttech.pojo.Employee;
import com.varasofttech.util.HibernateUtil;

/**
* @author Ranga Reddy
* @date Jan 25, 2015
* @version 1.0
* @description : Application.java
*/


public class Application {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

Employee employe = new Employee();
employe.setName("Ranga");
employe.setAge(27);
employe.setSalary(22000000);

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(employe);
transaction.commit();
session.close();

System.out.println("Employee Information : " +employe);
sessionFactory.close();
}
}


Output:
Custom generated Sequence value : Emp00001
Employee Information : Employee [id=Emp00001, name=Ranga, age=27, salary=2.2E7]

Happy Coding!!!

Thursday, January 22, 2015

CRUD Operations Using Hibernate

Below example explains how to perform Create, Read, Update and Delete (CRUD) operations using Hibernate.

Tools: 
Eclipse,
MySQL
Hiberante 4.3.6

Project Structure:


Step1: Creating the POJO class


Employee.java

package com.varasofttech.pojo;
import java.io.Serializable;
public class Employee implements Serializable {
private static final long serialVersionUID = -9001198124094210159L;

// properties
private long id; // identifier
private String name;
private int age;
private float salary;

public Employee() {
super();
}

public Employee(String name, int age, float salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}

// setters and getters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age
+ ", salary=" + salary + "]";
}
}


Step2: Creating the Mapping file (hbm.xml)

Employee.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"
>


<hibernate-mapping>
<class name="com.varasofttech.pojo.Employee" table="employees" >
<id name="id" column="e_id">
<generator class="increment"></generator>
</id>
<property name="name" column="e_name"></property>
<property name="age" column="e_age"/>
<property name="salary" column="e_salary"/>
</class>
</hibernate-mapping>

Step3: Creating the Configuration file (cfg.xml)


hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"
>


<hibernate-configuration>
<session-factory>

<!-- Database Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///vara_softtech</property>
<property name="hibernate.connection.username">varasofttech</property>
<property name="hibernate.connection.password">varasofttech</property>

<!-- Dialect class -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Hibernate specific -->
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.format_sql">true</property>

<mapping resource="Employee.hbm.xml"></mapping>

</session-factory>
</hibernate-configuration>

Step4: Creating the Utility class


HibernateUtil.java

package com.varasofttech.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

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

private static SessionFactory buildSessionFactory() {
try {

// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();

return configuration.buildSessionFactory(serviceRegistry);

} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static void closeSessionFactory() {
if(sessionFactory != null) {
sessionFactory.close();
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

Step5: Creating the Template class


HibernateTemplate .java

package com.varasofttech.dao.base;

import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.varasofttech.util.HibernateUtil;

public class HibernateTemplate {
private SessionFactory sessionFactory = null;

public HibernateTemplate() {
sessionFactory = HibernateUtil.getSessionFactory();
}

public Serializable save(Object entity) {
Serializable id = null;
Transaction transaction = null;
Session session = sessionFactory.openSession();
try {
transaction = session.beginTransaction();
id = session.save(entity);
transaction.commit();
} catch (RuntimeException e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return id;
}

public Object update(Object entity) {
Transaction transaction = null;
Session session = sessionFactory.openSession();
try {
transaction = session.beginTransaction();
session.update(entity);
transaction.commit();
} catch (RuntimeException e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return entity;
}

public Object findById(Serializable id, Class<?> clas) {
Session session = sessionFactory.openSession();
return session.get(clas, id);
}

public void delete(Serializable id, Class<?> clas ) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Object data = findById(id, clas);
session.delete(data);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

public List<?> findAll(Class<?> clas) {
Session session = sessionFactory.openSession();
Query query = session.createQuery( "from " + clas.getName());
return query.list();
}
}


Step6: Creating the Service class


EmployeeService.java

package com.varasofttech.service;

import java.util.List;
import com.varasofttech.dao.employee.EmployeeDAO;
import com.varasofttech.pojo.Employee;

public class EmployeeService {
private EmployeeDAO employeeDAO;

public EmployeeService() {
this.employeeDAO = new EmployeeDAO();
}

public Employee getEmployee(long employeeId) {
return this.employeeDAO.getEmployee(employeeId);
}

public long addEmployee(Employee employee) {
return this.employeeDAO.addEmployee(employee);
}

public void deleteEmployee(long employeeId) {
this.employeeDAO.deleteEmployee(employeeId);
}

public Employee updateEmployee(Employee employee) {
return this.employeeDAO.updateEmployee(employee);
}

public List<Employee> listEmployee() {
return this.employeeDAO.listEmployee();
}
}

Step7: Creating the DAO class

EmployeeDAO.java

package com.varasofttech.dao.employee;

import java.util.List;

import com.varasofttech.dao.base.HibernateTemplate;
import com.varasofttech.pojo.Employee;

public class EmployeeDAO {
private HibernateTemplate hibernateTemplate;

public EmployeeDAO() {
this.hibernateTemplate = new HibernateTemplate();
}

public Employee getEmployee(long employeeId) {
return (Employee) this.hibernateTemplate.findById(employeeId, Employee.class);
}

public long addEmployee(Employee employee) {
return (long) this.hibernateTemplate.save(employee);
}

public void deleteEmployee(long employeeId) {
this.hibernateTemplate.delete(employeeId, Employee.class);
}

public Employee updateEmployee(Employee employee) {
return (Employee) this.hibernateTemplate.update(employee);
}

@SuppressWarnings("unchecked")
public List<Employee> listEmployee() {
return (List<Employee>) this.hibernateTemplate.findAll(Employee.class);
}
}


Step8: Creating the Client class

Application.java

package com.varasofttech.client;

import java.util.List;

import com.varasofttech.pojo.Employee;
import com.varasofttech.service.EmployeeService;

public class Application {

public static void main(String[] args) {

EmployeeService employeeService = new EmployeeService();

Employee employee = new Employee("Ranga", 27, 300000);

System.out.println("Before Saving Employee Info : "+employee);

// CREATE
long employeeId = employeeService.addEmployee(employee);

// READ - Single Record
employee = employeeService.getEmployee(employeeId);
System.out.println("After Saving Employee Info : "+employee);

// READ - Multiple Records
System.out.println("Displaying all Employee Info : ");
List<Employee> employees = employeeService.listEmployee();
for (Employee employee2 : employees) {
System.out.println(employee2);
}

// UPDATE
employee.setName("Ranga Reddy");
employee.setAge(28);
employee = employeeService.updateEmployee(employee);
System.out.println("After Updation Employee Info : "+employee);

// DELETE
employeeService.deleteEmployee(employeeId);
employee = employeeService.getEmployee(employeeId);
System.out.println("After Deletion Employee Info : "+employee);

}
}

Happy Coding!!

Creating our Own Hibernate Template class

Let us see how to develop our own Hibernate Template class.

HibernateTemplate.java


import java.io.Serializable;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.varasofttech.util.HibernateUtil;

public class HibernateTemplate {
private SessionFactory sessionFactory = null;

public HibernateTemplate() {
sessionFactory = HibernateUtil.getSessionFactory();
}

public Serializable save(Object entity) {
Serializable id = null;
Transaction transaction = null;
Session session = sessionFactory.openSession();
try {
transaction = session.beginTransaction();
id = session.save(entity);
transaction.commit();
} catch (RuntimeException e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return id;
}

public Object update(Object entity) {
Transaction transaction = null;
Session session = sessionFactory.openSession();
try {
transaction = session.beginTransaction();
session.update(entity);
transaction.commit();
} catch (RuntimeException e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return entity;
}

public Object findById(Serializable id, Class<?> clas) {
Session session = sessionFactory.openSession();
return session.get(clas, id);
}

public void delete(Serializable id, Class<?> clas ) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Object data = findById(id, clas);
session.delete(data);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

public List<?> findAll(Class<?> clas) {
Session session = sessionFactory.openSession();
Query query = session.createQuery( "from " + clas.getName());
return query.list();
}
}

HibernateUtil.java

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

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

private static SessionFactory buildSessionFactory() {
try {

// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();

return configuration.buildSessionFactory(serviceRegistry);

} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static void closeSessionFactory() {
if(sessionFactory != null) {
sessionFactory.close();
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

Sunday, January 18, 2015

Caused by: java.lang.ClassNotFoundException: javax.servlet.SessionCookieConfig

Exception:

Caused by: java.lang.ClassNotFoundException: javax.servlet.SessionCookieConfig
        at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 38 more

Solution: We need to migrate Servlet version 2.5 to 3.0.1

The final dependency was

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>

Saturday, January 3, 2015

Hibernate Object Identity and Equality

There are several mismatches between the Object oriented system and Relation system. In that one of the important mismatch is Object identity and equality.

There are three ways to tackle identity: two ways in java world, and one is relational world. 

Java provides two ways for object identity and equality. 
  • If two objects are called identical when they point to the same reference in memory.
  • If two objects are considered equal when they contain similar data.
Java offers the equals() method and == operator to support equality and identity.
Employee employee1 = new  Employee("Ranga", 27, 35534);
Employee employee2 = employee1;
// identicality
System.out.println(employee1 == employee2); 
// equality
System.out.println(employee1.equals(employee2));

Note: When two objects are identical, they refer to the same memory location. Therefore, they have the same value and are definitely equal. However, two objects that are equal may not be identical since they may point to different locations in memory.
The identity of a Relational model is primary key.  Given a primary key we will 
always retrieve the same data.
To solve object oriented and relational mismatches( in that one identity and equality is one mismatch), orm tool is introduces. In that, Hibernate is one ORM tool. 
Lets see how Hibernate solve this identity and equality mismatch.
Entity (Employee.java) class:

package com.varasofttech.pojo;

import java.io.Serializable;

public class Employee implements Serializable {

private static final long serialVersionUID = -9001198124094210159L;

// properties
private long id; // identifier
private String name;
private int age;
private float salary;

public Employee() {
super();
}

public Employee(String name, int age, float salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}

// setters and getters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age
+ ", salary=" + salary + "]";
}
}


Client Application (Application.java)

package com.varasofttech.client;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.varasofttech.pojo.Employee;
import com.varasofttech.util.HibernateUtil;

public class Application {
public static void main(String[] args) {

// Object Identity and Equality - Java

String name1 ="Ranga";
String name2 = "Ranga";
String name3 = new String("Ranga");

// identical
System.out.println(name1 == name2);
System.out.println(name1 == name3);

// equals
System.out.println(name1.equals(name2));
System.out.println(name1.equals(name3));

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session1 = sessionFactory.openSession();

// Object Identity and Equality - Hibernate

Employee employee = new Employee("Ranga", 27, 30998);
Transaction transaction = session1.beginTransaction();
Long employeeId = (Long) session1.save(employee);
transaction.commit();

Employee employee1 = (Employee) session1.get(Employee.class, employeeId);
Employee employee2 = (Employee) session1.get(Employee.class, employeeId);

// identity
if( employee1 == employee2) {
System.out.println("Both employee objects are identical in same session");
} else {
System.out.println("Both employee objects are not identical in same session");
}

// equality
if( employee1.equals(employee2)) {
System.out.println("Both employee objects are equal in same session");
} else {
System.out.println("Both employee objects are not equal");
}

session1.close();

Session session2 = sessionFactory.openSession();
Employee employee3 = (Employee) session2.get(Employee.class, employeeId);

// identity
if( employee1 == employee3) {
System.out.println("Both employee objects are identical in another session");
} else {
System.out.println("Both employee objects are not identical in another session");
}

// equality
if( employee1.equals(employee3)) {
System.out.println("Both employee objects are equal in another session");
} else {
System.out.println("Both employee objects are not equal in another session");
}

session2.close();
sessionFactory.close();
}
}

Run the Client Application (Application.java)

true
false
true
true

Hibernate: select max(e_id) from employees
Hibernate: insert into employees (e_name, e_age, e_salary, e_id) values (?, ?, ?, ?)
Both employee objects are identical in same session
Both employee objects are equal in same session
Hibernate: select employee0_.e_id as e_id1_0_0_, employee0_.e_name as e_name2_0_0_, employee0_.e_age as e_age3_0_0_, employee0_.e_salary as e_salary4_0_0_ from employees employee0_ where employee0_.e_id=?
Both employee objects are not identical in another session
Both employee objects are not equal in another session

Now override equals() and  hashcode() in Entity(Employee.java) class.

package com.varasofttech.pojo;
import java.io.Serializable;

public class Employee implements Serializable {

private static final long serialVersionUID = -9001198124094210159L;

// properties
private long id; // identifier
private String name;
private int age;
private float salary;

public Employee() {
super();
}

public Employee(String name, int age, float salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}

// setters and getters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Float.floatToIntBits(salary);
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (age != other.age)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Float.floatToIntBits(salary) != Float.floatToIntBits(other.salary))
return false;
return true;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age
+ ", salary=" + salary + "]";
}
}

Now run the Client Application (Application.java)

true
false
true
true

Hibernate: select max(e_id) from employees
Hibernate: insert into employees (e_name, e_age, e_salary, e_id) values (?, ?, ?, ?)
Both employee objects are identical in same session
Both employee objects are equal in same session
Hibernate: select employee0_.e_id as e_id1_0_0_, employee0_.e_name as e_name2_0_0_, employee0_.e_age as e_age3_0_0_, employee0_.e_salary as e_salary4_0_0_ from employees employee0_ where employee0_.e_id=?
Both employee objects are not identical in another session
Both employee objects are equal in another session