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.

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}

Monday, February 2, 2015

The method getDispatcherType() is undefined for the type HttpServletRequest

An error occurred at line: [42] in the generated java file: [D:\Upgrade\Upgrade_Eclipse_Worlspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\Spring4Hiberante4Integration\org\apache\jsp\WEB_002dINF\pages\employeeList_jsp.java]

The method getDispatcherType() is undefined for the type HttpServletRequest

Solution:

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