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.

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>

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;
}
}