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, January 18, 2015

Caused by: java.lang.ClassNotFoundException: javax.servlet.SessionCookieConfig

Exception:

Caused by: java.lang.ClassNotFoundException: javax.servlet.SessionCookieConfig
        at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 38 more

Solution: We need to migrate Servlet version 2.5 to 3.0.1

The final dependency was

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

Saturday, January 3, 2015

Hibernate Object Identity and Equality

There are several mismatches between the Object oriented system and Relation system. In that one of the important mismatch is Object identity and equality.

There are three ways to tackle identity: two ways in java world, and one is relational world. 

Java provides two ways for object identity and equality. 
  • If two objects are called identical when they point to the same reference in memory.
  • If two objects are considered equal when they contain similar data.
Java offers the equals() method and == operator to support equality and identity.
Employee employee1 = new  Employee("Ranga", 27, 35534);
Employee employee2 = employee1;
// identicality
System.out.println(employee1 == employee2); 
// equality
System.out.println(employee1.equals(employee2));

Note: When two objects are identical, they refer to the same memory location. Therefore, they have the same value and are definitely equal. However, two objects that are equal may not be identical since they may point to different locations in memory.
The identity of a Relational model is primary key.  Given a primary key we will 
always retrieve the same data.
To solve object oriented and relational mismatches( in that one identity and equality is one mismatch), orm tool is introduces. In that, Hibernate is one ORM tool. 
Lets see how Hibernate solve this identity and equality mismatch.
Entity (Employee.java) class:

package com.varasofttech.pojo;

import java.io.Serializable;

public class Employee implements Serializable {

private static final long serialVersionUID = -9001198124094210159L;

// properties
private long id; // identifier
private String name;
private int age;
private float salary;

public Employee() {
super();
}

public Employee(String name, int age, float salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}

// setters and getters
public long getId() {
return id;
}
public void setId(long 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 + "]";
}
}


Client Application (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;

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

// Object Identity and Equality - Java

String name1 ="Ranga";
String name2 = "Ranga";
String name3 = new String("Ranga");

// identical
System.out.println(name1 == name2);
System.out.println(name1 == name3);

// equals
System.out.println(name1.equals(name2));
System.out.println(name1.equals(name3));

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session1 = sessionFactory.openSession();

// Object Identity and Equality - Hibernate

Employee employee = new Employee("Ranga", 27, 30998);
Transaction transaction = session1.beginTransaction();
Long employeeId = (Long) session1.save(employee);
transaction.commit();

Employee employee1 = (Employee) session1.get(Employee.class, employeeId);
Employee employee2 = (Employee) session1.get(Employee.class, employeeId);

// identity
if( employee1 == employee2) {
System.out.println("Both employee objects are identical in same session");
} else {
System.out.println("Both employee objects are not identical in same session");
}

// equality
if( employee1.equals(employee2)) {
System.out.println("Both employee objects are equal in same session");
} else {
System.out.println("Both employee objects are not equal");
}

session1.close();

Session session2 = sessionFactory.openSession();
Employee employee3 = (Employee) session2.get(Employee.class, employeeId);

// identity
if( employee1 == employee3) {
System.out.println("Both employee objects are identical in another session");
} else {
System.out.println("Both employee objects are not identical in another session");
}

// equality
if( employee1.equals(employee3)) {
System.out.println("Both employee objects are equal in another session");
} else {
System.out.println("Both employee objects are not equal in another session");
}

session2.close();
sessionFactory.close();
}
}

Run the Client Application (Application.java)

true
false
true
true

Hibernate: select max(e_id) from employees
Hibernate: insert into employees (e_name, e_age, e_salary, e_id) values (?, ?, ?, ?)
Both employee objects are identical in same session
Both employee objects are equal in same session
Hibernate: select employee0_.e_id as e_id1_0_0_, employee0_.e_name as e_name2_0_0_, employee0_.e_age as e_age3_0_0_, employee0_.e_salary as e_salary4_0_0_ from employees employee0_ where employee0_.e_id=?
Both employee objects are not identical in another session
Both employee objects are not equal in another session

Now override equals() and  hashcode() in Entity(Employee.java) class.

package com.varasofttech.pojo;
import java.io.Serializable;

public class Employee implements Serializable {

private static final long serialVersionUID = -9001198124094210159L;

// properties
private long id; // identifier
private String name;
private int age;
private float salary;

public Employee() {
super();
}

public Employee(String name, int age, float salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}

// setters and getters
public long getId() {
return id;
}
public void setId(long 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 int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Float.floatToIntBits(salary);
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (age != other.age)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Float.floatToIntBits(salary) != Float.floatToIntBits(other.salary))
return false;
return true;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age
+ ", salary=" + salary + "]";
}
}

Now run the Client Application (Application.java)

true
false
true
true

Hibernate: select max(e_id) from employees
Hibernate: insert into employees (e_name, e_age, e_salary, e_id) values (?, ?, ?, ?)
Both employee objects are identical in same session
Both employee objects are equal in same session
Hibernate: select employee0_.e_id as e_id1_0_0_, employee0_.e_name as e_name2_0_0_, employee0_.e_age as e_age3_0_0_, employee0_.e_salary as e_salary4_0_0_ from employees employee0_ where employee0_.e_id=?
Both employee objects are not identical in another session
Both employee objects are equal in another session

Wednesday, December 31, 2014

Explain about Hibernate Object Life Cycle?

In hibernate object life cycle, mainly consists of four states. They are 
  1. Transient State, 
  2. Persistent State, 
  3. Detached State and 
  4. Removed State.
Hibernate Object Life Cycle

1. New or Transient State:
When ever an object of a POJO class is Created(instantiated) using the new operator then it will be in the Transient state; this object is not associated with any Hibernate Session.
For example,
Employee employee = new Employee("Ranga", 27, 30998); // Transient
When we call delete() on persistent object then it also moves to transient state.
session.delete(employee); 
This object don’t have any association with any database table row. In other words any modification in data of transient state object doesn't have any impact on the database table. so their state is lost as soon as they’re no longer referenced by any other object.
Note: Transient objects exist in heap memory.
Transient state will be happened two scenarios:
  1. First where the objects are created by application but not connected to a session, and 
  2. Second the objects are created by a closed session.
Converting Transient State to Persistence State:
  • By saving the that object
    • session.save()
    • session.persist()
    • session.saveOrUpdate()
  • By loading that object from database
    • session.load()
    • session.get(),
    • session.byId()
    • session.byNaturalId() etc..
2. Persistent or Managed State:
In order to convert or move an object from Transient to Persistent, there are two ways.
  1. Saving the object to the database using session
  2. Loading the object from the database using session
In this state object known to the hibernate and represent a one row in the database. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes.
Different ways to Save an Object:
Hibernate supports the different ways to save an object to the database. They are
  • session.save()
  • session.saveOrUpdate()
  • session.persist()
For example,
Employee employee = new Employee("Ranga", 27, 30998); // Transient
session.save(employee); // persitent

Different Ways to Load an Object:
Hibernate supports the different ways to load an object from the database. Few of them are
  • session.get()
  • session.load()
  • session.byId()
  • session.byNaturalId() etc...
For example,
Employee employee = session.get(Employee.class, 1); // here employee object is associated   with session. So employee object state is Persistent.
Persistent State
We can covert the object from persistent state to detached state by clearing the cache of the session or close the session using evict(), clear() and close() methods.

Converting Persistent State to Detached State:
  • session.evict();
  • session.clear();
  • session.close();
3. Detached State:
In order to convert or move an object from Persistence to Detached State, we need to clear the cache of the session or close the session by using following methods.
  • session.evict();  - clear particular object from the cache
  • session.clear();  - clears all objects from the cache
  • session.close(); 
Employee employee = new Employee("Ranga", 27, 30998); // Transient
session.save(employee); // persitent
session.close(); // here employee state is detached because currently it is not associated with session.
Detached State
Changes made in this object does not reflect to the database. But we can change the state to persistent by calling following methods on detached object.
  • session.update()
  • session.merge()
  • session.saveOrUpdate()
Converting Detached State to Persistent State:
  • session.update()
  • session.merge()
  • session.saveOrUpdate()
4. Removed State:
This is last state in the hibernate object life cycle. A persistent object is considered to be in the removed state when a delete() operation is called on it. Note that Once you've deleted an object and moved to the “removed” state, you should no longer use that particular object for any reason.
For example:
session.delete(employee);
Removed State
Example:
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;

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

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();

// Hibernate Object Life Cycle

// New or Transient State begin
Employee employee = new Employee("Ranga", 27, 30998);
// New or Transient State end

System.out.println("Session Info in Transient State : ");
System.out.println(session);

// Persistent or Managed State begin
Transaction transaction = session.beginTransaction();
session.save(employee);
transaction.commit();
// Persistent or Managed State end

System.out.println("Session Info in Persistent State : ");
System.out.println(session);

// Detached State begin
session.evict(employee);
// Detached State end

System.out.println("Session Info in Detached State : ");
System.out.println(session);

// Persistent State begin
transaction = session.beginTransaction();
employee.setName("Ranga Reddy");
employee.setAge(27);

session.saveOrUpdate(employee);
transaction.commit();
// Persistent State end

System.out.println("Session Info in Persistent State : ");
System.out.println(session);

// Removed State begin
session.delete(employee);
// Removed State end

System.out.println("Session Info in Removed State : ");
System.out.println(session);

sessionFactory.close();
}

}

Output:

Session Info in Transient State : 
SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@59505b48 updates=org.hibernate.engine.spi.ExecutableList@4efac082 deletions=org.hibernate.engine.spi.ExecutableList@6bd61f98 orphanRemovals=org.hibernate.engine.spi.ExecutableList@48aca48b collectionCreations=org.hibernate.engine.spi.ExecutableList@13fd2ccd collectionRemovals=org.hibernate.engine.spi.ExecutableList@b9b00e0 collectionUpdates=org.hibernate.engine.spi.ExecutableList@506ae4d4 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@7d4f9aae unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])

Hibernate: select max(e_id) from employees
Hibernate: insert into employees (e_name, e_age, e_salary, e_id) values (?, ?, ?, ?)

Session Info in Persistent State :
SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.varasofttech.pojo.Employee#9]],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@59505b48 updates=org.hibernate.engine.spi.ExecutableList@4efac082 deletions=org.hibernate.engine.spi.ExecutableList@6bd61f98 orphanRemovals=org.hibernate.engine.spi.ExecutableList@48aca48b collectionCreations=org.hibernate.engine.spi.ExecutableList@13fd2ccd collectionRemovals=org.hibernate.engine.spi.ExecutableList@b9b00e0 collectionUpdates=org.hibernate.engine.spi.ExecutableList@506ae4d4 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@7d4f9aae unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])

Session Info in Detached State :
SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@59505b48 updates=org.hibernate.engine.spi.ExecutableList@4efac082 deletions=org.hibernate.engine.spi.ExecutableList@6bd61f98 orphanRemovals=org.hibernate.engine.spi.ExecutableList@48aca48b collectionCreations=org.hibernate.engine.spi.ExecutableList@13fd2ccd collectionRemovals=org.hibernate.engine.spi.ExecutableList@b9b00e0 collectionUpdates=org.hibernate.engine.spi.ExecutableList@506ae4d4 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@7d4f9aae unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])

Hibernate: update employees set e_name=?, e_age=?, e_salary=? where e_id=?

Session Info in Persistent State :
SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.varasofttech.pojo.Employee#9]],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@59505b48 updates=org.hibernate.engine.spi.ExecutableList@4efac082 deletions=org.hibernate.engine.spi.ExecutableList@6bd61f98 orphanRemovals=org.hibernate.engine.spi.ExecutableList@48aca48b collectionCreations=org.hibernate.engine.spi.ExecutableList@13fd2ccd collectionRemovals=org.hibernate.engine.spi.ExecutableList@b9b00e0 collectionUpdates=org.hibernate.engine.spi.ExecutableList@506ae4d4 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@7d4f9aae unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])

Session Info in Removed State :
SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.varasofttech.pojo.Employee#9]],collectionKeys=[]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@59505b48 updates=org.hibernate.engine.spi.ExecutableList@4efac082 deletions=org.hibernate.engine.spi.ExecutableList@6bd61f98 orphanRemovals=org.hibernate.engine.spi.ExecutableList@48aca48b collectionCreations=org.hibernate.engine.spi.ExecutableList@13fd2ccd collectionRemovals=org.hibernate.engine.spi.ExecutableList@b9b00e0 collectionUpdates=org.hibernate.engine.spi.ExecutableList@506ae4d4 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@7d4f9aae unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])


Monday, December 29, 2014

Explain about System.out.println()

System.out.println()

System is a final class available in java.lang package. It is a system related class and most of times make native calls.

Structure of System class:

public final class System {

public final static InputStream in = null;
public final static PrintStream out = null;
public final static PrintStream err = null;

private System() {

}

   public static void setIn(InputStream in) {
      
checkIO();
      
setIn0(in);
   }


  public static void setOut(PrintStream out) {
   
checkIO();
 setOut0(out);
}

   public static void exit(int status) {
      
Runtime.getRuntime().exit(status);
 
}

   public static void gc() {
      
Runtime.getRuntime().gc();
 
}
}

In the above System class, both err and out are instances of PrintStream class (java.io.PrintStream). System class has setters for all the three mentioned above but no getters. InputStream is again from java.io package.

out is a static field in a System class which is of type PrintStream ( a built in class available in java.io package, which contains several methods to print the different data values). In order to acess any static methods or static members we are using class name. So System.out

Structure of PrintStream:

public class PrintStream extends FilterOutputStream implements Appendable, Closeable {
  public PrntStream(OutputStream out) {    
       this(out, false);
  
}

    // Different arguments with print() and println() methods
      public void print() {
       
  
}
    
 public void println() {
       
  
}

    // printf() and format() methods

}

println - is a method of PrintStream class. println method prints the arguments passed to standard console and a new line. There are several print() and println() methods with different arguments. Every println() method makes a call to print() method and adds newline.



System is class in java.lang package and out is the instance of PrintStream class from java.io package and println() is a method from the PrintStream class.