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, 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(outfalse);
  
}

    // 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.

Compiling and Running Java program by using another Java program.



package com.ranga;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
Program: Compiling and Running Java program by using another Java program.
java.lang.Runtime.exec()
*/
public class Main {
public static void main(String[] args) {
System.out.println("I am in Main class begin.");
Process process = null;
try {
process = Runtime.getRuntime().exec("javac Test.java");
System.out.println("Test class successfully compiled.");
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}

try {
process = Runtime.getRuntime().exec("java Test");
printMessage(" stdout:", process.getInputStream());
System.out.println("Test class successfully runned.");
} catch (IOException ex) {
ex.printStackTrace();
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("I am in Main class end.");
} // end main()

private static void printMessage(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);
}
} // end printMessage()
} // end Main class



class Test {
public static void main(String a[]) {
System.out.println("I am in Test class");
}
}

Sunday, December 28, 2014

Different ways to get the Connection object using Hibernate

Getting the java.sql.Connection object using Session:
---------------------------------------------------------------------------

org.hibernate.Session is nothing but get the one physical connection from the database. 

By using Session we can get the Connection object several ways.

1) session.connection() - this method is deprecated. it is not available on Hibernate4.

2) session.doWork() - this method doesn't return Connection object, but inside what ever operation we want to do using connection object we can do. 

3) session.doReturningWork() - this method returns dynamic type value. In the below example i am return Connection object. 

4) SessionImpl.connection() - Down casting the Session object to SessionImpl. By using SessionImpl we will get the Connection object.

5) ConnectionProvider.getConnection() - Using ConnectionProvider getConnection() method.


Full Example:

package com.varasofttech.client;

import java.sql.Connection;
import java.sql.SQLException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.internal.SessionImpl;
import org.hibernate.jdbc.ReturningWork;
import org.hibernate.jdbc.Work;

import com.varasofttech.util.HibernateUtil;

public class Application {

public static void main(String[] args) {

// Different ways to get the Connection object using Session

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

// Way1 - using doWork method
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
// do your work using connection
}

});

// Way2 - using doReturningWork method
Connection connection = session.doReturningWork(new ReturningWork<Connection>() {
@Override
public Connection execute(Connection conn) throws SQLException {
return conn;
}
});

// Way3 - using Session Impl
SessionImpl sessionImpl = (SessionImpl) session;
connection = sessionImpl.connection();
// do your work using connection

// Way4 - using connection provider
SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session.getSessionFactory();
ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider();
try {
connection = connectionProvider.getConnection();
// do your work using connection
} catch (SQLException e) {
e.printStackTrace();
}
}
}


How to Create Custom Dialect class in Hibernate?

Creating a Custom Dialect in Hibernate:

In order to create any new Dialect class we need to extends org.hibernate.dialect.Dialect class. Dialect class is a abstract class.

If you look at the Dialect class,

public abstract class Dialect implements ConversionContext {
protected Dialect() {
// here we are registering the functions, ColumnType, HibernateTypes
// for registering function's we can use registerFunction() method.
// for registering columntype's we can use registerColumnType() method.
// for registering hibernatetype's we can use registerHibernateType() method.
}
// some others methods
}

For connecting MySQL database, Hibernate people created a dialect class called 'org.hibernate.dialect.MySQLDialect'.

public class MySQLDialect extends MySQLDialect {
      public MySQLDialect() {
  // here they resisted mysql functions, column types
}
// some other methods
}

In the same way, in order to connect with Oracle database, hibernate people developed a 5 dialect classes based on Oracle Version.

org.hibernate.dialect.OracleDialect
org.hibernate.dialect.Oracle8iDialect
org.hibernate.dialect.Oracle9Dialect
org.hibernate.dialect.Oracle9iDialect
org.hibernate.dialect.Oracle10gDialect

if you see the OracleDialect class signature

public class OracleDialect extends Oracle9Dialect {
public OracleDialect() {
// here they resisted oracle functions, column types
}
}

Now we can see how to create Custom Dialect classes.

My requirement is, based on current time, i want to display greeting message say for example if time is 10:01:59 AM then i need to display "Morning" other time is 14:12:15 PM then i need to display "Afternoon". So for this one there is no function exists in any database. 

so for this one what i did is, i created one function in mysql database i.e say_gretting and i am using that function. In order to use that function i need to one new class and extends MySQLDialect class. Finally i need to register say_greeting function in Custom dialect class.

package com.varasofttech.dialect;

import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.function.StandardSQLFunction;

public class VaraSoftTechMySQLDialect extends MySQL5Dialect {
public VaraSoftTechMySQLDialect() {
super();
// here i am registring custom function to display greeting message.
registerFunction("say_greeting", new StandardSQLFunction("say_greeting"));
}
}

Finally this dialect class, we need to register in hiberante.cfg.xml file.


<!-- Dialect class -->
<property name="hibernate.dialect">com.varasofttech.dialect.VaraSoftTechMySQLDialect</property>

Now lets see how to create 'say_greeting' function in mysql.


DROP FUNCTION IF EXISTS say_greeting;
DELIMITER $$
CREATE FUNCTION say_greeting(name TEXT)
RETURNS TEXT
BEGIN
DECLARE greetingMessage CHAR(10);
SET greetingMessage = (SELECT IF((SELECT TIME_FORMAT(now(),'%H') from DUAL) < 12,'Morning', IF((SELECT TIME_FORMAT(now(),'%H') from DUAL) < 15,'Afternoon','Evening')));
RETURN CONCAT('Hello ', name, ', Good ', greetingMessage, '!');
END;
$$
DELIMITER ;

SELECT say_greeting('ranga') from DUAL;

Now write client application in order to use say_greeting function. Here i am using NativeSQLQuery.


        Configuration configuration = new Configuration();
configuration.configure(
"hibernate.cfg.xml");

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();

SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();


SQLQuery query = session.createSQLQuery("SELECT say_greeting('ranga') from DUAL");

String greetingMessage = (String) query.list().get(0);
System.out.println(greetingMessage);

session.close();

sessionFactory.close();

Output:

Dec 29, 2014 6:45:09 AM org.hibernate.dialect.Dialect <init>

INFO: HHH000400: Using dialect: com.varasofttech.dialect.VaraSoftTechMySQLDialect

Hibernate: 
    SELECT
        say_greeting('ranga') 
    from

        DUAL

Hello ranga, Good Evening!

Reference:
http://myjourneyonjava.blogspot.in/2014/12/displaying-greeting-message-based-on.html

Happy Coding!!!!