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, January 24, 2014

Downloading Spring Framework

Click here to Download

Tuesday, January 14, 2014

Externalization in Java


In my previous post ( Serialization), we saw about Serialization. While using Serialization we can get some limitations.

Limitations of Serialization:
  1. File size is very high because it contains meta information of the file.
  2. Customization due to transient which is not effective because we get “null” in place of transient attributes.
To overcome the limitations of Serialization, we can use the Externalization.

Externalization(java.io.Externalizable): 

Externalization is nothing but serialization but by implementing Externalizable interface to persist and restore the object. To make our object as externalize we need to implement with Externalizable interface.

Unlike Serializable interface, it is not a marker interface which contains two methods 

public void writeExternal(ObjectOutput out) throws IOException;
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;

In Serialization process, JVM has full control for serializing object but in Externalization process application/developer gets control for persisting objects. In Externalization process, writeExternal() and readExternal() method provides complete control on format and content of Serialization process.

In writeExternal() method we are making attributes as externalized by using corresponding methods for different types of data.

writeInt()    --> for Integer
writeLong() --> for Long
writeDouble() --> for Double
writeUTF()    --> for String (UTF --> Universal Text Format)
writeObject() --> for Derived attributes other than String & Wrapper classes etc..

In the same way, readExternal() method also provides some methods. By using those methods we can get the externilized attributes.

readInt();
readLong();
readDouble();
readUTF();
readObject();

Employee.java

package com.ranga;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

/**
 * Created by ranga on 1/12/14.
 */

public class Employee implements Externalizable {
  private long serialVersionUID = 31462223600l;

  private long id;
  private String firstName;
  private String lastName;
  private int age;
  private String address;

  public Employee() {
    super();
  }

  public Employee(long id, String firstName, String lastName, int age, String address) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.address = address;
  }
  public Employee(int age) {
    this.age = age;
  }

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

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  @Override
  public void writeExternal(ObjectOutput out) throws IOException {
    out.writeLong(id);
    out.writeUTF(firstName);
    out.writeUTF(lastName);
    out.writeInt(age);
    out.writeUTF(address);
  }

  @Override
  public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    id = in.readLong();
    firstName = in.readUTF();
    lastName = in.readUTF();
    age = in.readInt();
    address = in.readUTF();
  }

  @Override
  public String toString() {
    return "Employee{" +
        "id=" + id +
        ", firstName='" + firstName + '\'' +
        ", lastName='" + lastName + '\'' +
        ", age=" + age +
        ", address='" + address + '\'' +
        '}';
  }

}

ExternalizationDemo.java

package com.ranga;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

/**
 * Created by ranga on 1/13/14.
 */

public class ExternalizationDemo {
  public static void main(String[] args) {
    Employee employee = new Employee();
    employee.setId(143);
    employee.setFirstName("Ranga");
    employee.setLastName("Reddy");
    employee.setAge(25);
    employee.setAddress("MPL, Chittoor, AP");

    FileOutputStream fileOutputStream = null;
    ObjectOutputStream objectOutputStream = null;

    try {
      fileOutputStream = new FileOutputStream( new File("employees.ser"));
      objectOutputStream = new ObjectOutputStream(fileOutputStream);
      objectOutputStream.writeObject(employee);
      System.out.println("Employee Object Externalization Done Successfully.");
    } catch(Exception ex) {
      ex.printStackTrace();
    } finally {
      if(objectOutputStream != null) {
        try {
          objectOutputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
      if(fileOutputStream != null) {
        try {
          fileOutputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
    }
  }
}

Output:
Employee Object Externalization Done Successfully.

DeExternalizationDemo.java

package com.ranga;

import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * Created by ranga on 1/13/14.
 */
public class DeExternalizationDemo {
  public static void main(String[] args) {
    FileInputStream fileInputStream = null;
    ObjectInputStream objectInputStream = null;

    try {
      fileInputStream = new FileInputStream(new File("employees.ser"));
      objectInputStream = new ObjectInputStream(fileInputStream);
      Employee employee = (Employee) objectInputStream.readObject();
      System.out.println("Employee Info: "+employee);
    } catch(Exception ex) {
      ex.printStackTrace();
    } finally {
      if(objectInputStream != null) {
        try {
          objectInputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
      if(fileInputStream != null) {
        try {
          fileInputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
    }
  }
}

Output:
Employee Info: Employee{id=143, firstName='Ranga', lastName='Reddy', age=25, address='MPL, Chittoor, AP'}

Only those fields will be persisted as byte stream that will be saved by writeExternal and readExternal. Other field in the class will not be externalized. So by Externalizable interface java developer has complete control on java class persistence.

Externalizable provides complete control, it also presents challenges to serialize super type state and take care of default values in case of transient variable and static variables in Java. If used correctly Externalizable interface can improve performance of serialization process.

Advantages:

The main advantages of externalization over serialization are:
1)File size is highly reduced(nearly 1/3)
2) Customization is very easy and more effective.

Performance issue:
 
1. Further more if you are subclassing your externalizable class you will want to invoke your superclass’s implementation. So this causes overhead while you subclass your externalizable class.
2. methods in externalizable interface are public. So any malicious program can invoke which results into lossing the prior serialized state.


Difference between Serialization and Externalization:

1. With the classes which implement Serializable, the serialization of the object is taken care of automatically, while classes that implement Externalizable is responsible for serializing itself, without the help of default serialization procedures.
2. when we serialize an Externalizable object, a default constructor will be called automatically after that will the readExternal() method be called.

Sunday, January 12, 2014

How to get the System Properties and System Environment variables by using Java

  1. To get the System properties we can use getProperty() of System class. 
  2. To get all the System properties we can use the getProperties() of System class.

package com.ranga;

/**
 * Created by ranga on 1/12/14.
 */

public class Application {
  public static void main(String[] args) {
    System.out.println("Java Version: "+ System.getProperty("java.version"));
  }
}

Output:
Java Version: 1.6.0_35


Fetching all System properties.
---------------------------------------------------------------
package com.ranga;

import java.util.Map;
import java.util.Properties;

/**
 * Created by ranga on 1/12/14.
 */

public class Application1 {
  public static void main(String[] args) {
    Properties properties = System.getProperties();
    for(Object key : properties.keySet()) {
      System.out.println("Key: "+ key +", Value: "+properties.getProperty(key.toString()));
    }
  }
}

Output:

Key: java.runtime.name, Value: Java(TM) SE Runtime Environment
Key: sun.boot.library.path, Value: /usr/java/jdk1.6.0_35/jre/lib/amd64
Key: java.vm.version, Value: 20.10-b01
Key: java.vm.vendor, Value: Sun Microsystems Inc.
Key: java.vendor.url, Value: http://java.sun.com/
Key: path.separator, Value: :
Key: idea.launcher.port, Value: 7554
Key: java.vm.name, Value: Java HotSpot(TM) 64-Bit Server VM
Key: file.encoding.pkg, Value: sun.io
Key: sun.java.launcher, Value: SUN_STANDARD
Key: user.country, Value: US
Key: sun.os.patch.level, Value: unknown
Key: java.vm.specification.name, Value: Java Virtual Machine Specification
Key: user.dir, Value: /home/ranga/install/ITappCloud/SerializationExample
Key: java.runtime.version, Value: 1.6.0_35-b10
Key: java.awt.graphicsenv, Value: sun.awt.X11GraphicsEnvironment
Key: java.endorsed.dirs, Value: /usr/java/jdk1.6.0_35/jre/lib/endorsed
Key: os.arch, Value: amd64
Key: java.io.tmpdir, Value: /tmp
Key: line.separator, Value:

Key: java.vm.specification.vendor, Value: Sun Microsystems Inc.
Key: os.name, Value: Linux
Key: sun.jnu.encoding, Value: UTF-8
Key: java.library.path, Value: /usr/java/jdk1.6.0_35/jre/lib/amd64/server:/usr/java/jdk1.6.0_35/jre/lib/amd64:/usr/java/jdk1.6.0_35/jre/../lib/amd64:/home/ranga/Softwares/idea-IU-133.193/bin::/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
Key: java.specification.name, Value: Java Platform API Specification
Key: java.class.version, Value: 50.0
Key: sun.management.compiler, Value: HotSpot 64-Bit Tiered Compilers
Key: os.version, Value: 3.9.10-100.fc17.x86_64
Key: user.home, Value: /home/ranga
Key: user.timezone, Value:
Key: java.awt.printerjob, Value: sun.print.PSPrinterJob
Key: idea.launcher.bin.path, Value: /home/ranga/Softwares/idea-IU-133.193/bin
Key: file.encoding, Value: UTF-8
Key: java.specification.version, Value: 1.6
Key: java.class.path, Value: /usr/java/jdk1.6.0_35/jre/lib/plugin.jar:/usr/java/jdk1.6.0_35/jre/lib/rt.jar:/usr/java/jdk1.6.0_35/jre/lib/deploy.jar:/usr/java/jdk1.6.0_35/jre/lib/management-agent.jar:/usr/java/jdk1.6.0_35/jre/lib/charsets.jar:/usr/java/jdk1.6.0_35/jre/lib/resources.jar:/usr/java/jdk1.6.0_35/jre/lib/jce.jar:/usr/java/jdk1.6.0_35/jre/lib/javaws.jar:/usr/java/jdk1.6.0_35/jre/lib/jsse.jar:/usr/java/jdk1.6.0_35/jre/lib/ext/sunjce_provider.jar:/usr/java/jdk1.6.0_35/jre/lib/ext/sunpkcs11.jar:/usr/java/jdk1.6.0_35/jre/lib/ext/localedata.jar:/usr/java/jdk1.6.0_35/jre/lib/ext/dnsns.jar:/home/ranga/install/ITappCloud/SerializationExample/target/classes:/home/ranga/Softwares/idea-IU-133.193/lib/idea_rt.jar
Key: user.name, Value: ranga
Key: java.vm.specification.version, Value: 1.0
Key: sun.java.command, Value: com.intellij.rt.execution.application.AppMain com.ranga.MyTest2
Key: java.home, Value: /usr/java/jdk1.6.0_35/jre
Key: sun.arch.data.model, Value: 64
Key: user.language, Value: en
Key: java.specification.vendor, Value: Sun Microsystems Inc.
Key: java.vm.info, Value: mixed mode
Key: java.version, Value: 1.6.0_35
Key: java.ext.dirs, Value: /usr/java/jdk1.6.0_35/jre/lib/ext:/usr/java/packages/lib/ext
Key: sun.boot.class.path, Value: /usr/java/jdk1.6.0_35/jre/lib/resources.jar:/usr/java/jdk1.6.0_35/jre/lib/rt.jar:/usr/java/jdk1.6.0_35/jre/lib/sunrsasign.jar:/usr/java/jdk1.6.0_35/jre/lib/jsse.jar:/usr/java/jdk1.6.0_35/jre/lib/jce.jar:/usr/java/jdk1.6.0_35/jre/lib/charsets.jar:/usr/java/jdk1.6.0_35/jre/lib/modules/jdk.boot.jar:/usr/java/jdk1.6.0_35/jre/classes
Key: java.vendor, Value: Sun Microsystems Inc.
Key: file.separator, Value: /
Key: java.vendor.url.bug, Value: http://java.sun.com/cgi-bin/bugreport.cgi
Key: sun.io.unicode.encoding, Value: UnicodeLittle
Key: sun.cpu.endian, Value: little
Key: sun.desktop, Value: gnome
Key: sun.cpu.isalist, Value:
 

--------------------------------------------------------------------------------------------------------------

To get System environment variables we can use the System.getenv() method.

package com.ranga;

import java.util.Map;

/**
 * Created by ranga on 1/12/14.
 */

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

    Map<String, String> env = System.getenv();
    for(String key : env.keySet()) {
      System.out.println(key +" --> "+env.get(key));
    }

  }
}

The main difference between System.getProperty() and System.getenv() is
System.getProperty() is for JVM arguments which are passed -DpropName=value to java application launcher(java) and System.getenv() is for Operating System environment variables.


Sorting and Searching the Employee Object by using Collection

In this post, we can learn how to sort the Employee object by using age and search the Employee object by using age.

Employee.java
----------------------------------------

package com.ranga;

import java.io.Serializable;

/**
 * Created by ranga on 1/12/14.
 */

public class Employee implements Serializable {
  private long serialVersionUID = 31462223600l;

  private long id;
  private String firstName;
  private String lastName;
  private int age;
  private String address;

  public Employee() {
    super();
  }

  public Employee(long id, String firstName, String lastName, int age, String address) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.address = address;
  }
  public Employee(int age) {
    this.age = age;
  }

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

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  @Override
  public String toString() {
    return "Employee{" +
        "id=" + id +
        ", firstName='" + firstName + '\'' +
        ", lastName='" + lastName + '\'' +
        ", age=" + age +
        ", address='" + address + '\'' +
        '}';
  }

}

Application.java

package com.ranga;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by ranga on 1/12/14.
 */
public class Application {
  public static void main(String[] args) {
    Employee employee = new Employee();
    employee.setId(1);
    employee.setFirstName("Ranga");
    employee.setLastName("Reddy");
    employee.setAge(25);
    employee.setAddress("MPL, Tirupathi, AP");

    Employee employee2 = new Employee();
    employee2.setId(2);
    employee2.setFirstName("Ranga");
    employee2.setLastName("Reddy");
    employee2.setAge(27);
    employee2.setAddress("BTM, Bangalore, KA");

    Employee employee3 = new Employee();
    employee3.setId(3);
    employee3.setFirstName("Ranga");
    employee3.setLastName("Reddy");
    employee3.setAge(22);
    employee3.setAddress("Bommanahalli, Bangalore, KA");

    List<Employee> employees = new ArrayList<Employee>();
    employees.add(employee);
    employees.add(employee2);
    employees.add(employee3);

    System.out.println("Before Sorting...");
    for(Employee emp : employees) {
      System.out.println(emp);
    }
    System.out.println("*******************************************************");
    Collections.sort(employees, new Comparator<Employee>() {
      @Override
      public int compare(Employee o1, Employee o2) {
        return o1.getAge() - o2.getAge();
      }
    });

    System.out.println("After Sorting...");
    for(Employee emp : employees) {
      System.out.println(emp);
    }
    System.out.println("*******************************************************");
    int index = Collections.binarySearch(employees, new Employee(25), new Comparator<Employee>() {
      @Override
      public int compare(Employee o1, Employee o2) {
        return o1.getAge() - o2.getAge();
      }
    });

    if(index != -1) {
      System.out.println("Employee found at location : "+index);
      System.out.println(employees.get(index));
    } else {
      System.out.println("Employee not found..");
    }
    System.out.println("*******************************************************");

  }
}

Output:

Before Sorting...
Employee{id=1, firstName='Ranga', lastName='Reddy', age=25, address='MPL, Tirupathi, AP'}
Employee{id=2, firstName='Ranga', lastName='Reddy', age=27, address='BTM, Bangalore, KA'}
Employee{id=3, firstName='Ranga', lastName='Reddy', age=22, address='Bommanahalli, Bangalore, KA'}
*******************************************************
After Sorting...
Employee{id=3, firstName='Ranga', lastName='Reddy', age=22, address='Bommanahalli, Bangalore, KA'}
Employee{id=1, firstName='Ranga', lastName='Reddy', age=25, address='MPL, Tirupathi, AP'}
Employee{id=2, firstName='Ranga', lastName='Reddy', age=27, address='BTM, Bangalore, KA'}
*******************************************************
Employee found at location : 1
Employee{id=1, firstName='Ranga', lastName='Reddy', age=25, address='MPL, Tirupathi, AP'}
*******************************************************

Serialization in Java

 

Serialization:

Serialization is a process of writing the object state into a file system with extension .ser and recreatign object state from that file(this is called deserialization). Generally objects are stored in the Memory. In order to store the object permanently we can use the Serialization process.

In order to make any object as Serialization we need to implement with java.io.Serializable interface. Serializable interface is marker interface which doesn't have any method but it tells to the compiler this class is serializable.

Serialization process is JVM independent. It means an object can be serialized on one platform and deserialized on an different platform or same platform.

The process of serializing an object is also called marshalling an object. The process of deserializing an object is also called unmarshalling.

Serialization has a number of advantages. It provides:

Serialization can be achived two ways:
  1. Object itself should be qualifiy as a Serializable
  2.  Already implemented Seriablizable interfaces.

To make an object is serializable we can use the ObjectOutputStream class and for deserializable we can use the ObjectInputStream class.

In ObjectOutputStream class contains a lot of methods in that one method called writeObject() by using this method we can make the object as serializable.
public final void writeObject(Object obj) throws IOException;

In the same way in ObjectInputStream class contains a method called readObject() by using this method we can make the object as deserializable.
public final Object readObject() throws IOException, ClassNotFoundException;

The return type of readObject() is Object, so we need to type cast into appropriate data type.

By default all of the fields serializable while doing serialization. If you don't want any field as serializable, then mark that field as transient.

Employee.java
------------------------------------

package com.ranga;

import java.io.Serializable;

/**
 * Created by ranga on 1/12/14.
 */

public class Employee implements Serializable {
  private static final long serialVersionUID = 9986183183l;
  private long id;
  private String firstName;
  private String lastName;
  private int age;
  private String address;

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

  public String getAddress() {
    return address;
  }

  public void setAddress(String address) {
    this.address = address;
  }

  @Override
  public String toString() {
    return "Employee{" +
        "id=" + id +
        ", firstName='" + firstName + '\'' +
        ", lastName='" + lastName + '\'' +
        ", age=" + age +
        ", address='" + address + '\'' +
        '}';
  }

}

SerializationDemo.java
------------------------------------

package com.ranga;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

/**
 * Created by ranga on 1/12/14.
 */

public class SerializationDemo {
  public static void main(String[] args) {
    Employee employee = new Employee();
    employee.setId(143);
    employee.setFirstName("Ranga");
    employee.setLastName("Reddy");
    employee.setAge(25);
    employee.setAddress("MPL, Chittoor, AP");

    FileOutputStream fileOutputStream = null;
    ObjectOutputStream objectOutputStream = null;

    try {
      fileOutputStream = new FileOutputStream( new File("employee.ser"));
      objectOutputStream = new ObjectOutputStream(fileOutputStream);
      objectOutputStream.writeObject(employee);
      System.out.println("Employee Object Serialization Done Successfully.");
    } catch(Exception ex) {
      ex.printStackTrace();
    } finally {
       if(objectOutputStream != null) {
         try {
           objectOutputStream.close();
         } catch(Exception ex) {
           ex.printStackTrace();
         }
       }
      if(fileOutputStream != null) {
        try {
          fileOutputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
    }
  }
}

Output:
------------------------------------
Employee Object Serialization Done Successfully.

DeSerializationDemo.java
------------------------------------
package com.ranga;

import java.io.*;

/**
 * Created by ranga on 1/12/14.
 */
public class DeSerializationDemo {
  public static void main(String[] args) {
    FileInputStream fileInputStream = null;
    ObjectInputStream objectInputStream = null;

    try {
      fileInputStream = new FileInputStream(new File("employee.ser"));
      objectInputStream = new ObjectInputStream(fileInputStream);
      Employee employee = (Employee) objectInputStream.readObject();
      System.out.println("Employee Info: "+employee);
    } catch(Exception ex) {
      ex.printStackTrace();
    } finally {
      if(objectInputStream != null) {
        try {
          objectInputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
      if(fileInputStream != null) {
        try {
          fileInputStream.close();
        } catch(Exception ex) {
          ex.printStackTrace();
        }
      }
    }
  }
}

Output:
------------------------------------
Employee Info: Employee{id=143, firstName='Ranga', lastName='Reddy', age=25, address='MPL, Chittoor, AP'}

If a super class is implementing Serializable interface, then all sub classes are eligible for Serialization.

Example:

public class Person implements Serializable {

}
public class Employee extends Person {

}

By default, all wrapper classes are implemented Serializable.

Limitations:
  1. File size is considerable more because it contains meta information.
  2. Less performance if more transient attributes.
So in order to overcome the above limitations we can use the Externilization. We can see this one in next tutorial.

Saturday, January 11, 2014

Write a SQL program to accept the users birthdate and calculates the Age.


create table Persons(id int, name varchar2(40), dob date);

insert into Persons values(1,'ranga','01-JUN-88');
insert into Persons values(2,'eswar','01-JUL-88');
insert into Persons values(3,'vinod','01-APR-87');

1. SELECT p.*, trunc( (sysdate - dob) / 365.25) as age FROM Persons p;
2. SELECT p.*, floor(months_between(sysdate,dob)/12) age FROM Persons p;
3. SELECT  p.*, trunc((sysdate - p.dob)/365.25) as age FROM Persons p;

Output:



Displaying the Year Month Day
-----------------------------------------------------

SELECT trunc(months_between(sysdate,dob)/12) as YEAR,
       trunc(mod(months_between(sysdate,dob),12)) as MONTH,
       trunc(sysdate - add_months(dob,trunc(months_between(sysdate,dob)/12) *12 + trunc(MOD(months_between(sysdate,dob),12)))) DAY
FROM (SELECT p.dob dob FROM Persons p);



Thursday, January 9, 2014

Finding the Nth heighest Salary in SQL

Program: 

Write a SQL query to get the Nth highest salary from Employee table. Here N can be any number.

Solution:

SELECT e.* FROM Employee e;


Step1: If you want to find the height salary, initially you need to sort the employee data in descending order or if you want to find the lowest salary you need to sort the employee data in ascending.


Here i am finding the height salary so i will sort the employee data in descending order.

SELECT e.* FROM Employee e ORDER By e.salary DESC;


Step2: After Sorting the data, now give the rownum to the table. 

SELECT ROWNUM rn, Emp.* FROM (SELECT e.* FROM Employee e ORDER By e.salary DESC) Emp;





Step3: Finally, which highest salary do you want to find give that value in where condition.

Here i am finding the 3rd heighest employee information.

SELECT * FROM(SELECT ROWNUM rn, Emp.* FROM (SELECT e.* FROM Employee e ORDER By e.salary DESC) Emp) WHERE rn=3;



Note: rownum works some of the databases only example oracle



MySQL:

mysql>CREATE TABLE Employee(id INT NOT NULL AUTO_INCREMENT,
   firstname VARCHAR(50) NOT NULL,
   lastname VARCHAR(50),
   salary INT,
   designation varchar(5),
   PRIMARY KEY (id));

Query OK, 0 rows affected (0.12 sec)

mysql> INSERT INTO Employee(firstname, lastname, salary, designation) values('ranga','reddy',50000,'Software Engineer');
Query OK, 1 row affected, 1 warning (0.06 sec)

mysql> INSERT INTO Employee(firstname, lastname, salary, designation) values('vinod','reddy',170000,'Software Developer');
Query OK, 1 row affected, 1 warning (0.06 sec)

mysql> INSERT INTO Employee(firstname, lastname, salary, designation) values('raja','reddy',7000,'Trainee Test Engineer');
Query OK, 1 row affected, 1 warning (0.05 sec)

mysql> INSERT INTO Employee(firstname, lastname, salary, designation) values('vasu','reddy',79000,'Test Engineer');
Query OK, 1 row affected, 1 warning (0.05 sec)

mysql> INSERT INTO Employee(firstname, lastname, salary, designation) values('manu','reddy',90,'Engineer');
Query OK, 1 row affected, 1 warning (0.04 sec)

mysql> select * from Employee;
+----+-----------+----------+--------+-------------+
| id | firstname | lastname | salary | designation |
+----+-----------+----------+--------+-------------+
|  1 | ranga     | reddy    |  50000 | Softw       |
|  2 | vinod     | reddy    | 170000 | Softw       |
|  3 | raja      | reddy    |   7000 | Train       |
|  4 | vasu      | reddy    |  79000 | Test        |
|  5 | manu      | reddy    |     90 | Engin       |
+----+-----------+----------+--------+-------------+
5 rows in set (0.00 sec)

Sort the Employee data in Ascending because i am finding the Nth lowest salary.

mysql> select * from Employee e order by e.salary;
+----+-----------+----------+--------+-------------+
| id | firstname | lastname | salary | designation |
+----+-----------+----------+--------+-------------+
|  5 | manu      | reddy    |     90 | Engin       |
|  3 | raja      | reddy    |   7000 | Train       |
|  1 | ranga     | reddy    |  50000 | Softw       |
|  4 | vasu      | reddy    |  79000 | Test        |
|  2 | vinod     | reddy    | 170000 | Softw       |
+----+-----------+----------+--------+-------------+
5 rows in set (0.00 sec)

In mysql there is keyword called limit is used to find out the limit number of records.

mysql> select * from Employee e order by e.salary limit 2;
+----+-----------+----------+--------+-------------+
| id | firstname | lastname | salary | designation |
+----+-----------+----------+--------+-------------+
|  5 | manu      | reddy    |     90 | Engin       |
|  3 | raja      | reddy    |   7000 | Train       |
+----+-----------+----------+--------+-------------+
2 rows in set (0.00 sec)

In the above example i passed limit value as 2 so it displayed only 2 records. Here Limit is keyword is taking only one argument.

There is one more limit it will take two arguments one is offset and second is maximum number of rows return.

Syntax looks like Limit N-1, No.of records

For example i want to find the 1st lowest employee information then i need to pass like 1-1, 1 ==> 0,1

mysql> select * from Employee e order by e.salary limit 0,1;
+----+-----------+----------+--------+-------------+
| id | firstname | lastname | salary | designation |
+----+-----------+----------+--------+-------------+
|  5 | manu      | reddy    |     90 | Engin       |
+----+-----------+----------+--------+-------------+
1 row in set (0.00 sec)


In the next example we will see finding the top n records.







Caused by: java.sql.SQLSyntaxErrorException: ORA-00918: column ambiguously defined

Caused by: java.sql.SQLSyntaxErrorException: ORA-00918: column ambiguously defined

Problem: The problem comes from while triggering a select query. In select query the multiple tables having the same column name but if we specified with out any prefix then it will throws the column ambiguously defined.

Example: Assume it two table Student and Employee. Both tables is having id, id.

Then while fetching the recored

Select id, * from Student s, Employee e;

Solution: Add prefix to the column

Select s.id, e.id, * from Student s, Employee e;

Note: Columns must be referenced as TABLE.COLUMN or TABLE_ALIAS.COLUM .

Wednesday, January 8, 2014

Write the program to generate following triangle. 1 1 3 1 3 5 1 3 5 7

Program:

  Write the program to generate following triangle.
  1
  1 3
  1 3 5
  1 3 5 7

Code:

package com.ranga;

class TriangleDemo
{
    public static void main (String[] args)
    {
        int temp = 0;
        for(int i=0; i< 4; i++) {
            for(int j = 0; j<=i; j++) {
                if(j == 0) {
                  temp = j + 1;
                } else {
                  temp = temp + 2;   
                }
                System.out.print(temp+" ");
            }
            System.out.println();
        }
    }
}

Output:

1 
1 3
1 3 5
1 3 5 7
 
You can also see live example in ideone.
http://ideone.com/ie8lmD 

Thursday, January 2, 2014

Component Mapping in Hibernate


A Component (Embedded Object) is an object that is persisted as a value type, not an entity (table). A Component mapping is a mapping for a class having a reference to another class as a member variable.

Consider the following Person class














Person class contains the following properties like firstName, lastName, age, houseNo, street etc. Instead of keeping the all attributes in one class(Person) we can divide the some properties(house, street, city) into separate class (Address) and map that attribute to Person class.



























In the above example, Address is a component in the Person class and it  can't have its own primary key, it uses the primary key of the enclosing Person entity.

Generally we can use, to get the form data from multiple pages and save the data into a single table.

Components can in turn declare their own properties, components or collections.

<component
       name="propertyName"                               
       class="className"                                 
       insert="true|false"                               
       update="true|false"                               
       access="field|property|ClassName"                  
       lazy="true|false"                                  
       optimistic-lock="true|false"                       
       unique="true|false"                                
       node="element-name|."
>
       <property ...../>
       <many-to-one .... />
       ........
</component>


name: the name of the property.
class (optional - defaults to the property type determined by reflection): the name of the component (child) class.
insert: do the mapped columns appear in SQL INSERTs?
update: do the mapped columns appear in SQL UPDATEs?
access (optional - defaults to property): the strategy Hibernate uses for accessing the property value.
lazy (optional - defaults to false): specifies that this component should be fetched lazily when the instance variable is first accessed. It requires build-time bytecode instrumentation.
optimistic-lock (optional - defaults to true): specifies that updates to this component either do or do not require acquisition of the optimistic lock. It determines if a version increment should occur when this property is dirty.
unique (optional - defaults to false): specifies that a unique constraint exists upon all mapped columns of the component.


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;
   private Address address;
   
   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;
   }
   public Address getAddress() {
       return address;
   }
   public void setAddress(Address address) {
       this.address = address;
   }
   @Override
   public String toString() {
       return "Person [id=" + id + ", firstName=" + firstName + ", lastName="
               + lastName + ", age=" + age + ", address=" + address + "]";
   }
       
}


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


import java.io.Serializable;


public class Address implements Serializable {
   private String houseNo;
   private String street;
   private String city;
   public String getHouseNo() {
       return houseNo;
   }
   public void setHouseNo(String houseNo) {
       this.houseNo = houseNo;
   }
   public String getStreet() {
       return street;
   }
   public void setStreet(String street) {
       this.street = street;
   }
   public String getCity() {
       return city;
   }
   public void setCity(String city) {
       this.city = city;
   }
   @Override
   public String toString() {
       return "Address [houseNo=" + houseNo + ", street=" + street + ", city="
               + city + "]";
   }    
   
}


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


   <class name="Person" table="Persons">
       <id name="id">
           <generator class="increment"/>                        
       </id>
       <property name="firstName" />
       <property name="lastName" />
       <property name="age" />
       <component name="address" class="Address">
           <property name="houseNo"></property>
           <property name="street"></property>
           <property name="city"></property>                        
       </component>        
   </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>


       <!-- Enable Hibernate's automatic session context management -->
       <property name="current_session_context_class">thread</property>


       <!-- Disable the second-level cache -->
       <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</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">update</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.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;


import com.ranga.mapping.Address;
import com.ranga.mapping.Person;
import com.ranga.util.HibernateUtil;


public class App {
   public static void main(String[] args) {
       SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
       // Saving the Person Information
       Session session = sessionFactory.openSession();
       Transaction transaction = null;
       try {
           transaction = session.beginTransaction();


           Address address = new Address();
           address.setHouseNo("124");
           address.setStreet("BTM");
           address.setCity("Bangalore");


           Person p1 = new Person();
           p1.setFirstName("ranga");
           p1.setLastName("reddy");
           p1.setAge(25);
           p1.setAddress(address);


           long personId = (Long) session.save(p1);
           transaction.commit();


           // fetching the Person Information
           Person person = (Person) session.get(Person.class, personId);
           System.out.println(person);


       } catch (HibernateException e) {
           transaction.rollback();
           e.printStackTrace();
       } finally {
           session.close();
       }
   }
}

=====================================================================