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.

Sunday, March 1, 2015

Inheritance in Hibernate

Inheritance in Hibernate: 

Java is object oriented language and inheritance is one of main functionalities of java. Relational model can implement "is a" and "has a" relationship. Relational model supports only “has a” relationship between two entities. Hibernate can help you map such Objects with relational tables. But you need to choose certain mapping strategy based on your needs. There are three inheritance mapping strategies defined in the hibernate.


  • One table per one concrete class (TABLE_PER_CLASS)
  • One table per all hierarchical classes (SINGLE_TABLE)
  • One table per one concrete sub class (JOINED)


One table per one concrete class: This mapping is not known as good mapping for projects. In this approach every entity class has its own table i.e. table per class. All the properties of a class including inherited properties are mapped to columns of a table.

There are two ways to map the table with table per concrete class strategy.
  1. By using <union-subclass> element.
  2. By self creating the table for each class.

Lets say we have following class hierarchy.

We have Person class as base class and Employee  is subclass of Person and PermanentEmployee is Subclass of Employee.

In  table per concrete class, One table will be created for each concrete class. So there table will be three tables created( Person, Employee and PermanenetEmployee) and subclass repeats property of parent class.

Person.java
==============
package com.ranga.mapping;

import java.io.Serializable;

public class Person implements Serializable {
   private long id;
   private String firstName;
   private String lastName;
   private int age;
   // Constructors and Getter/Setter methods,
   public long getId() {
       return id;
   }
   public void setId(long id) {
       this.id = id;
   }
   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 int getAge() {
       return age;
   }
   public void setAge(int age) {
       this.age = age;
   }        
}


Employee.java
====================

package com.ranga.mapping;

public class Employee extends Person {
   private String designation;
   private Double salary;
   // Constructors and Getter/Setter methods,
   public String getDesignation() {
       return designation;
   }
   public void setDesignation(String designation) {
       this.designation = designation;
   }
   public Double getSalary() {
       return salary;
   }
   public void setSalary(Double salary) {
       this.salary = salary;
   }    
}


PermanentEmployee.java
=========================
package com.ranga.mapping;


public class PermanentEmployee extends Employee {
   private double allowance;
   private int noOfLeaves;
   // Constructors and Getter/Setter methods,
   public double getAllowance() {
       return allowance;
   }
   public void setAllowance(double allowance) {
       this.allowance = allowance;
   }
   public int getNoOfLeaves() {
       return noOfLeaves;
   }
   public void setNoOfLeaves(int noOfLeaves) {
       this.noOfLeaves = noOfLeaves;
   }    
}

1. By self creating the table for each class:

Person.hbm.xml
========================
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ranga.mapping">
   <!-- Table-per-class hierarchy -->
   <class name="Person" table="Persons">
       <id name="id" />
       <property name="firstName" />
       <property name="lastName" />
       <property name="age" />        
   </class>
   <class name="Employee" table="Employees">
       <id name="id" />
       <property name="designation" />
       <property name="salary" />        
   </class>
   
   <class name="PermanentEmployee" table="PermanentEmployees">
       <id name="id" />
       <property name="allowance" />
       <property name="noOfLeaves" />        
   </class>        
</hibernate-mapping>


2. By using <union-subclass> element:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.ranga.mapping">
   <!-- Table-per-class hierarchy -->
   <class name="Person" table="Persons">
       <id name="id" />
       <property name="firstName" />
       <property name="lastName" />
       <property name="age" />
       <union-subclass name="Employee" table="Employees">
           <property name="designation" />
           <property name="salary" />
       </union-subclass>      
       <union-subclass name="PermanentEmployee" table="PermanentEmployees">
           <property name="allowance" />
           <property name="noOfLeaves" />
       </union-subclass>        
   </class>    
</hibernate-mapping>

hibernate.cfg.xml
====================
<?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>
       <!-- Database connection settings -->
       <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
       <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
       <property name="connection.username">ranga</property>
       <property name="connection.password">ranga</property>

       <!-- JDBC connection pool (use the built-in) -->
       <property name="connection.pool_size">1</property>

       <!-- SQL dialect -->
       <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>

     <!-- Echo all executed SQL to stdout -->
       <property name="show_sql">true</property>

       <!-- Drop and re-create the database schema on startup -->
       <property name="hbm2ddl.auto">create</property>


       <mapping resource="com/ranga/mapping/Person.hbm.xml" />
   </session-factory>
</hibernate-configuration>

HibernateUtil.java
=======================
package com.ranga.util;


import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
   private static final SessionFactory sessionFactory;
   private static final ServiceRegistry serviceRegistry;
   static {
       try {
           Configuration configuration = new Configuration();
           configuration.configure();
           serviceRegistry = new ServiceRegistryBuilder().applySettings(
                   configuration.getProperties()).buildServiceRegistry();
           sessionFactory = configuration.buildSessionFactory(serviceRegistry);
       } catch (Throwable ex) {
           throw new ExceptionInInitializerError(ex);
       }
   }

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


App.java
======================
package com.ranga;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.ranga.mapping.Employee;
import com.ranga.mapping.PermanentEmployee;
import com.ranga.mapping.Person;
import com.ranga.util.HibernateUtil;

public class App
{
    public static void main( String[] args )
    {
       SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
       Session session = sessionFactory.openSession();
       session.beginTransaction();
       
       Person p1= new Person();
       p1.setId(1);
       p1.setFirstName("ranga");
       p1.setLastName("reddy");
       p1.setAge(25);
       
       Employee e1= new Employee();
       e1.setId(2);
       e1.setFirstName("raja");
       e1.setLastName("reddy");
       e1.setAge(45);
       e1.setDesignation("Project Lead");
       e1.setSalary(120000.0);
       
       PermanentEmployee pe1= new PermanentEmployee();
       pe1.setId(3);
       pe1.setFirstName("vasundra");
       pe1.setLastName("reddy");
       pe1.setAge(40);
       pe1.setDesignation("Architect");
       pe1.setSalary(150000.0);
       pe1.setNoOfLeaves(15);
       pe1.setAllowance(5000.00);
       
       session.save(p1);
       session.save(e1);
       session.save(pe1);
       
       session.getTransaction().commit();        
    }
}

[all common attributes will be duplicated]

Advantage:
  • Simple and efficient
  • Possible to define NOT NULL constraints on the table.

Disadvantage:
  • if you have a query against the super class, you will have to query several times for each sub-class tables.
  • Change in super class properties will have to be reflected in changes in each sub-class tables.
  • Data thats belongs to a parent class is scattered across a number of subclass tables, which represents concrete classes.
  • This hierarchy is not recommended for most cases.

Note: In this case there no need for the discriminator column because all entity has own table.
 

Friday, February 27, 2015

Exception in thread "main" org.hibernate.MappingException: Cannot use identity column key generation with mapping for:


Exception in thread "main" org.hibernate.MappingException: Cannot use identity column key generation with <union-subclass> mapping for: com.varasofttech.pojo.table_per_concrete_class.PermanentEmployee
    at org.hibernate.persister.entity.UnionSubclassEntityPersister.<init>(UnionSubclassEntityPersister.java:96)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:163)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:135)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:401)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859)
at com.varasofttech.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:36)
at com.varasofttech.util.HibernateUtil.getSessionFacoty(HibernateUtil.java:22)
at com.varasofttech.client.Application.main(Application.java:22)
Entity:
@Entity
@Table(name="Persons")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Person implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
// some other properties
}
Problem:
Hibernate does not support the use of identity or increment generation strategy for "table per concrete class with union strategy".

@Entity
@Table(name="Persons")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Person implements Serializable {

@Id
@GeneratedValue(strategy=GenerationType.TABLE)
private long id;
// some other properties

}

org.hibernate.MappingException: Unknown entity

Problem:
This exception will occur mainly because of the following two reasons

1. Making the @Entity with the wrong annotation

import org.hibernate.annotations.Entity; 
@Entity
public class Employee implements Serializable {
...
}
solution for this one is changing the package name.
import javax.persistence.Entity;
2. Missing the @Entity annotation

public class Employee implements Serializable {
...
}

solution for this one is adding the @Entity annotation to the class.

import javax.persistence.Entity;

@Entity
public class Employee implements Serializable {

}


Happy Coding!!!

Thursday, February 26, 2015

Tomcat Remote debugging from Eclipse

To enable debug on tomcat, set the following line in your catalina.bat

DEBUG_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

From your eclipse, create a Run Configuration for 'Remote Java Application' on socket 8000 and restart tomcat.

Wednesday, February 4, 2015

Hibernate4 Logging Configuration Example

Hibernate 4.0 onwords for logging the information, JBoss Logging library are used. It is similar to SLF4J, Jakarta's Common logging, it is "logging bridge" provides the integration with several logging frameworks (Log4J, SLF4j, JDK Logging). Hibernate people is chosen JBoss Logging because it supports the I18N and support for "Message ids".

Step1: Create a Maven project
Create a maven project using one of your favorite IDE. Here i used Intellij Idea.

Step2: Update the Maven Dependencies
Update pom.xml file to include required dependencies
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.varasofttech</groupId>
<artifactId>Hibernate4LoggingExample</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Hibernate4 Logging Example</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<hiberante-version>4.3.7.Final</hiberante-version>
<log4j-version>1.2.17</log4j-version>
<mysql-version>5.1.34</mysql-version>
<junit-version>4.11</junit-version>
</properties>

<dependencies>

<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hiberante-version}</version>
</dependency>

<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-version}</version>
</dependency>

<!-- Log4J -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j-version}</version>
</dependency>

<!--JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>

</dependencies>
</project>
Step3: Create a Log4j properties file
Create a "log4j.properties" file and put it into your project’s classpath.

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Direct messages to file hibernate.log
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D://Hibernate4/hibernate.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Root logger
log4j.rootLogger=INFO, file, stdout

log4j.logger.org.hibernate=INFO

# log JDBC bind parameters
log4j.logger.org.hibernate.type=ALL

# log HQL query parser activity
log4j.logger.org.hibernate.hql.ast.AST=INFO

# log just the SQL
log4j.logger.org.hibernate.SQL=trace

# log schema export/update
log4j.logger.org.hibernate.tool.hbm2ddl=DEBUG

# log HQL parse trees
log4j.logger.org.hibernate.hql=INFO

# log cache activity
log4j.logger.org.hibernate.cache=INFO

# log JDBC resource acquisition
log4j.logger.org.hibernate.jdbc=DEBUG

Step4: Hibernate 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>
<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.password">varasofttech</property>
<property name="hibernate.connection.username">varasofttech</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>

<mapping class="com.varasofttech.entity.Employee" />
</session-factory>
</hibernate-configuration>
Step5: Hibernate Utility Class
HibernateUtil.java
package com.varasofttech.util;
import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
/**
* @author Ranga Reddy
* @date Feb 4, 2015.
* @version 1.0
*/

public class HibernateUtil {
private static SessionFactory sessionFactory = null;
private static Logger logger = Logger.getLogger(HibernateUtil.class);

public static SessionFactory getSessionFactory() {
if(sessionFactory == null) {
try {
// Create the SessionFactory from hibernate.cfg.xml
String configurationFile = "hibernate-cfg.xml";
Configuration configuration = new Configuration();
configuration.configure(configurationFile);
logger.info("Hibernate Configuration loaded successfully using "+configurationFile);
StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder();
ServiceRegistry serviceRegistry = standardServiceRegistryBuilder.applySettings(configuration.getProperties()).build();
logger.info("Hibernate serviceRegistry object created successfully");

SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
logger.info("Hibernate sessionFactory object created successfully");
return sessionFactory;
}
catch (Throwable ex) {
logger.error("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
return sessionFactory;
}
}
Step6: Client Application
Application.java

package com.varasofttech;

import com.varasofttech.entity.Employee;
import com.varasofttech.util.HibernateUtil;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
/**
* @author Ranga Reddy
* @date Feb 4, 2015
* @version 1.0
*/

public class Application {
public static void main( String[] args ) {
Logger logger = Logger.getLogger(Application.class);

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Employee employee = new Employee("Ranga Reddy", 27, 35000);
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.save(employee);
transaction.commit();
logger.info("Employee object saved successfully. Employee Info : "+employee);
} catch (Exception ex) {
transaction.rollback();
logger.info("Exception occured while saving the Employee object :", ex);
} finally {
if(transaction != null) {
transaction = null;
}
if(session != null) {
session.close();
session = null;
}
}
}
}
Hibernate.log
07:57:31,482  INFO Dialect:145 - HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
07:57:32,823  INFO TransactionFactoryInitiator:62 - HHH000399: Using default transaction strategy (direct JDBC transactions)
07:57:32,869 INFO ASTQueryTranslatorFactory:47 - HHH000397: Using ASTQueryTranslatorFactory
07:57:33,100 TRACE TypeFactory:72 - Scoping types to session factory org.hibernate.internal.SessionFactoryImpl@6a2f6f80
07:57:35,771 INFO SchemaExport:343 - HHH000227: Running hbm2ddl schema export
07:57:35,774 DEBUG SchemaExport:353 - Import file not found: /import.sql
07:57:35,785 DEBUG SQL:109 - drop table if exists Employees
07:57:36,111 DEBUG SQL:109 - create table Employees (id bigint not null auto_increment, age integer, name varchar(255), salary float, primary key (id))
07:57:36,751 INFO SchemaExport:405 - HHH000230: Schema export complete
07:57:36,825 INFO HibernateUtil:31 - Hibernate sessionFactory object created successfully
07:57:37,819 DEBUG SQL:109 - insert into Employees (age, name, salary) values (?, ?, ?)
07:57:37,896 TRACE BasicBinder:81 - binding parameter [1] as [INTEGER] - [27]
07:57:37,900 TRACE BasicBinder:81 - binding parameter [2] as [VARCHAR] - [Ranga Reddy]
07:57:37,904 TRACE BasicBinder:81 - binding parameter [3] as [FLOAT] - [35000.0]
07:57:38,106 INFO Application:27 - Employee object saved successfully. Employee Info : Employee{id=1, name='Ranga Reddy', age=27, salary=35000.0}
Console log
07:57:31,482  INFO Dialect:145 - HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
07:57:32,823 INFO TransactionFactoryInitiator:62 - HHH000399: Using default transaction strategy (direct JDBC transactions)
07:57:32,869 INFO ASTQueryTranslatorFactory:47 - HHH000397: Using ASTQueryTranslatorFactory
07:57:33,100 TRACE TypeFactory:72 - Scoping types to session factory org.hibernate.internal.SessionFactoryImpl@6a2f6f80
07:57:35,771 INFO SchemaExport:343 - HHH000227: Running hbm2ddl schema export
07:57:35,774 DEBUG SchemaExport:353 - Import file not found: /import.sql
07:57:35,785 DEBUG SQL:109 - drop table if exists Employees
Hibernate: drop table if exists Employees
07:57:36,111 DEBUG SQL:109 - create table Employees (id bigint not null auto_increment, age integer, name varchar(255), salary float, primary key (id))
Hibernate: create table Employees (id bigint not null auto_increment, age integer, name varchar(255), salary float, primary key (id))
07:57:36,751 INFO SchemaExport:405 - HHH000230: Schema export complete
07:57:36,825 INFO HibernateUtil:31 - Hibernate sessionFactory object created successfully
07:57:37,819 DEBUG SQL:109 - insert into Employees (age, name, salary) values (?, ?, ?)
Hibernate: insert into Employees (age, name, salary) values (?, ?, ?)
07:57:37,896 TRACE BasicBinder:81 - binding parameter [1] as [INTEGER] - [27]
07:57:37,900 TRACE BasicBinder:81 - binding parameter [2] as [VARCHAR] - [Ranga Reddy]
07:57:37,904 TRACE BasicBinder:81 - binding parameter [3] as [FLOAT] - [35000.0]
07:57:38,106 INFO Application:27 - Employee object saved successfully. Employee Info : Employee{id=1, name='Ranga Reddy', age=27, salary=35000.0}