Monday, June 27, 2016

Java Collections class methods example



package com.corejava.collection;
import java.util.*;
class CollectionsDemo
{
public static void main(String[] args)
{
  List list = new ArrayList();
  list.add(20);
  list.add(2);
  list.add(34);
  list.add(1);
  list.add(5);
  list.add(45);

  //Using Collections class method, we can do many operation, lets do with one by one

  //As we know , list can hold the insertion order, if you want to reverse the insertion order,
  //Use the Collections.reverse(list) method to reverse the elements from list

  Collections.reverse(list);

  //If you want to sort the elements accoridng the asscending order then we can use

  Collections.sort(list);
  //If you want to find the Maximum or Minimum elements from the list then

  Collections.max(list);
  Collections.min(list);

  //If you want to synchronize the list, which is not a synchronized then

  Collections.synchronizedCollection(list);
  // Or
  Collections.synchronizedList(list);

  Collections.shuffle(list);
  System.out.println(" List is :"+list.toString());

  HashMap map = new HashMap();
  map.put("one", 1);
  map.put("two", 2);
  map.put("three", 3);
  //for synchronizing the map using the collections class
  Collections.synchronizedMap(map);
 
 Set  set = new HashSet();
 set.add(10);
 set.add(2);
 set.add(23);
 set.add(44);
 set.add(1);
 Collections.max(set);
 Collections.min(set);
 Collections.synchronizedSet(set);//or
 Collections.synchronizedCollection(set);  
     }
}

Friday, June 24, 2016

Spring Bean Scoops

Spring support 5 types of bean scoops


  1. Singleton : singleton scope will return same object reference if you call multiple time to the bean from the IOC Container.
  2. Prototype  : It will return new object reference of the bean for every request we do with IOC  Container.
  3. Request : Return single bean instance per HTTP request.
  4. Session  : Return single bean instance per HTTP Session
  5. Global session : Returns single bean instance per HTTP Global Session.
  6. Application(V4.0): 
 Example of Singleton Scope: 
import com.javacontainer.service.customer;
public class CustomerService 
{
String message;
public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}

Bean Configuration in Configuration xml file


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

       
            class="com.javacontainer.service.customer.CustomerService" />
Calling the Bean
package com.javacontainer.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.javacontainer.service.customer.CustomerService;

public class App 
{
    public static void main( String[] args )
    {
    ApplicationContext context = 
    new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"});

    CustomerService custA = (CustomerService)context.getBean("customerService");
    custA.setMessage("Message by custA");
    System.out.println("Message : " + custA.getMessage());
   
    //retrieve it again
    CustomerService custB = (CustomerService)context.getBean("customerService");
    System.out.println("Message : " + custB.getMessage());
    }
}

OutPut:

 Message : Message by custA
 Message : Message by custA


Example of Prototype Scope of Bean Configuration




xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

       
            class="com.javacontainer.service.customer.CustomerService"  scope="prototype"/>

OutPut

Message : Message by custA
Message : null

Bean Scope Configuration using Annotation :

package com.javacontainer.service.customer.CustomerService;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")
public class CustomerService 
{
String message;
public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}

To Read the annotation by the IOC Container we need to configure the element inside the spring configuration file :


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

       





Wednesday, June 22, 2016

How to call a finalize method with different ways


To  call a finalize method from a code , we have different ways.

There are different ways to call a Garbage Collector to remove the non reference object, but we can't say exact what time will it remove the object from the memory.
Below are the following few ways to call the garbage collector.

1. System.gc():

  Example :  
                     Class Test{
                           public static void main(String[] args{
                                 Test t = new Test();
                                System.gc();
                           }
                       }

2. Object reference of your class dot finalize() method
   
      Example :  
                     Class Test{

                           public static void main(String[] args{
                           
                                 Test t = new Test();
                                  t.finalize();//Here we are calling garbage collector by using the finalize method
                           }
                       }
3. System.runFinalization():
 
This will tell the Garbage Collector to give me preference to remove  the objects
Example:

       public static void main(String args[]){
Test t=new Test();
 t.setName("ganesh");
System.runFinalization();
 System.out.println("Name is :"+t.getName());

}

Monday, June 20, 2016

Translating JSP scriptlet code to servlet service life cycle method

Scriptlets are nothing but java code enclosed within <% and %> tags. JSP container moves the statements enclosed in it to _jspService()method while generating servlet from JSP. The reason of copying this code to service method is: For each client’s request the _jspService() method gets invoked, hence the code inside it executes for every request made by client.
Syntax of Scriptlet:
[code language=”java”]<% Executable java code%>[/code]

JSP to Servlet transition for Scriptlet –

As I stated in my previous tutorials that JSP doesn’t get executed directly, it first gets converted into a Servlet and then Servlet execution happens as normal. Also, I explained in first para that while translation from JSP to servlet, the java code is copied from scriptlet to _jspService() method. Lets see how that happens.
Sample JSP code:
[code language=”html”]

Sample JSP


<% myMethod();%>
[/code]
Note: Semicolon at the end of scriptlet.
Corresponding translated Servlet code for above JSP code:
[code language=”java”]
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
JspWriter out = response.getWriter();
out.println("

Sample JSP

");
myMethod();
}[/code]

Friday, June 17, 2016

How to call a store procedure from hibernate?

Creating Stored Procedure in MYSQL

mysql> DELIMITER //
mysql> create procedure usp_totalEmployeeByDeparment(IN id INT)
    -> begin
    -> select count(*) as total from employee where dept_id = id;
    -> end//

Calling Stored Procedure from mysql command line

MYSQL >  CALL usp_totalEmployeeByDepartment(100);



How to call Stored Procedure from hibernate native sql and named query 


Native SQL
Query query = session.createSQLQuery(
"CALL usp_totalEmployeeByDeparment(:id)").addEntity(Employee.class).setParameter("id", 7277);

List result = query.list();
for(int i=0; i Employee emp= (Employee)result.get(i);
System.out.println(emp.getDepartment());
}

Named Query

Query query = session.getNamedQuery("usp_totalEmployeeByDeparment").setParameter("id", 7277);
List result = query.list();
for(int i=0; i Employee emp= (Employee )result.get(i);
System.out.println(emp.getDepartment());
}

Saturday, June 11, 2016

What is the difference among session.evict(),session.clear() and session.close()?

In Hibernate we have two kinds of cache first level and second level, for the first level cache will be associated with the session object of hibernate.where we are going to store the retrieved object from the data base for further use in the application.
For some scenario we have to remove those persisted object from the session object, to do that we have to use the following session methods.

  1. session.evict()
  2. session.clear()
  3. session.close()
Session.evict() :
  • Session.evict() method is used to remove the single object from the session.
           Session session = factory.openSession();
           Object obj1 = session.get(Student.class,new Integer(101));
           Student student = (Student)obj1;
          Object obj2 = session.get(Student.class,new Integer(102));
          Student student2 = (Student) obj2;
           //Here session object is associated with student objects obj1 and obj2 at first level cache to remove only one  student object obj1 from session cache, we have to use the session method evict()

          session.evict(obj1); //Here we are removed obj1 object from session object
session.clear()
  • session.clear() method is used to remove all the persisted objects from the session first level cache.
      Session session = factory.openSession();
           Object obj1 = session.get(Student.class,new Integer(101));
           Student student = (Student)obj1;
          Object obj2 = session.get(Student.class,new Integer(102));
          Student student2 = (Student) obj2;
           //Here session object is associated with student objects obj1 and obj2 at first level cache to remove both   student objects obj1 and obj2 from session cache, we have to use the session method clear().

          session.clear(); //Here we are removed obj1  and obj2 object from session object

session.close()
  • session.close() method is used to close the session object associated with the session factory, which is no more exits to perform the data base operation using the persistent class and first level cache also automatically not available.
      Session session = factory.openSession();
           Object obj1 = session.get(Student.class,new Integer(101));
           Student student = (Student)obj1;
          Object obj2 = session.get(Student.class,new Integer(102));
          Student student2 = (Student) obj2;
           //Here session object is associated with student objects obj1 and obj2 at first level cache. If you  close the session object  both   student objects obj1 and obj2 from session cache will be deleted along with the session object, we have to use the session method close().

          session.close(); //Here we are closing session object, simultaneously both obj1 and obj2 also removed from the session.




           

Friday, June 10, 2016

Difference between Hibernate SessionFactory and Session interfaces

Session Factory


  • Session Factory is a heavy weight object, because it need to read the mapping file, configuration file and other configuration file to create one session factory object.that why we call it as heavy weight object.
  • Session Factory is a thread safe object, no two threads access simultaneously  and session factory object will be one per application.
  • Session Factory is a factory which is going to create a no of session objects which are light weight.
  • Session Factory is responsible for creating and  managing the session objects.
  • Session Factory object will be created one per application and it will be 
                SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();


Session

  • Session is a light weight object and not thread safe. i.e it can access multiple thread simultaneously.
  • Session object is used to interact with the data base to perform CRUD(Create, Read, Update, Delete) Operations.
  • Session is one per request and it will hold the data base connection when  we call the CRUD operation, we call it as lazy initializing. 
           SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();
                                    Session session=sessionFactory.openSession();

Avoiding Too Many connection of Session in hibernate using ThreadLocal class to get the current session without creating multiple times

import java.lang.ThreadLocal;
import org.hibernate.Session;

import org.hibernate.SessionFactory;
import org.hibernate.HibernateException;

public class HibernateUtil
{
    public static final ThreadLocal local = new ThreadLocal();

    // Creating Session Factory Object
    SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();

    // To get the current Session object from Session Factory object
    public static Session currentSession() throws HibernateException
    {
       Session session = (Session) local.get();

       //open a new session if this thread has no active session
       if(session == null)
       {
          session = sessionFactory.openSession();
          local.set(session);
       }

       return session;
    }
}