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.

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>

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