Caching in Hibernate


Caching is a Temporary memory or buffer which resides at client side and stores the results sent by server. When client generates same request for multiple number of times, the first request generated results will be stored in cache and this result will be used across the multiple requests. This reduces the round trips between the client and server. Since the result will be collected from cache that is available at client side.

Hibernate supports for 2 levels of cache:

  1. Level one cache
  2. Level two cache.

Level One Cache:

Level 1 cache is inbuilt cache and it will be associated with hibernate session objects. Every session object of hibernate application contains one inbuilt level one cache.

Responsibilities of Level one cache:

a)      If select query executed for multiple no of times with in a session. Only one time query goes to database software gets the result, remaining all the times result will be gathered from cache.

b)      If one of pojo class object is modified for multiple no of times with in a transaction of session object, instead of sending update query for multiple number of times, all the changes done on the object wil be kept tracked and only one update query wil be generated reflecting all the changes at the end of the transaction.

The different ways to remove the level 1 cache from session

i)                    Session.flush() –>  Flushes level one cache content to db software

ii)                   Session.evict() –> Remove the content of level 1 cache

iii)                 Session.close() –> closes level 1 cache, before that it calls session.flush()

A hibernate client application can have multiple level1 caches because a hibernate application can have multiple hibernate session objects.

The data stored in level1 cache, level2 cache will be in full synchronization with table rows.

Level-2 Cache:

It is a configurable cache (Not a built in cache). Third party vendors are supplying supporting jar files for level 2 cache. Level2 cache is global cache and it is visible for all the session objects of the hibernate application.

When level-2 cache is enabled the results gathered for database software will be stored in both level 1 and level 2 caches.

sessionFactory.close() –> Destroys the session factory object and releases level 2 cache.

sessionFactory.evict(arga …) –> Removes pojo class object from session factory.

sessionFactory.evictQueries(args…) –> Cleans queries related data from cache.

If hibernate use same request as second request or different session objects then software tries to collects the results either from leve1/level2 caches.

There are different third party providers for level 2 cache:

  1. Swarm Cache
  2. OS Cache,
  3. EH Cache
  4. JBoss Tree Cache … etc.

Replace String Example in Java


/**
 * @author Mallikarjun G
 *
 */
public class JavaStringReplaceExample {
    /**
     * @param args
     */
    public static void main(String args[]) {      
        String str = “Replace String”;
        System.out.println(str.replace(‘R’, ‘A’));// Replaceing R with a in str
        System.out.println(str.replaceFirst(“Re”, “Ra”));// Replaceing First Re with Ra in str  
        System.out.println(str.replaceAll(“Re”, “Ra”)); // Replaceing All Re with Ra in str   

    }
}

Connecting SQL Server using Java/JDBC


Below program consists of steps to connect SQL server using JDBC

package com.javatutorials;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SqlServerConnection {
public static Connection connection = null;
public static Connection getDbConnection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager
.getConnection("jdbc:odbc:mydsn;user=sa;password=sa12$");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}

public static void closeConnection() {
if (connection != null)
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Create Folder in Java Example


import java.io.File;
/**
 * @author mallikarjung
 *
 */
public class FolderCreation {
    public static String folderPath = “D:/SampleFolder/”;
    /**
     * @param args
     */
    public static void main(String[] args) {
        File folder = new File(folderPath);
        //check whether folder exists or not
        if(!folder.exists()){
            folder.mkdir();
            System.out.println(“Folder has been created Successfully … “);
        }
    }
}

Difference between Struts and JSF


Struts is an Action framework and JSF is component framework.
Action Framework: Struts (both 1 and 2) are action frameworks. In essence they give you the ability to map URLs to activities and code on the back end. Here, the layout and workflow tends to be more page oriented. As a developer you tend to interact with the HTTP request cycle directly, though Struts 2 helps isolate at least the binding of the request data to the action implementation classes.
Action framework coders can have more control of the structure and presentation of URLs, since their systems are more intimately tied to them compared to a component framework.
Component Framework: In a component framework, artifacts that are rendered on the page are initially developed as individual components, much like in modern GUI “fat client” libraries. You have components, they have events, and your code is written to work with those events against the components. Most of the time, in mainstream development, your code is pretty much ignorant of the HTTP request cycle and processing.
JSF eliminated the need of Form Bean and DTO classes as it allows the use of same pojo class on all tiers of the application because of the Backing Bean.
In struts framework we can access the request and response objects directly, as in case of JSF we can access request and response objects indirectly.
Struts has a more sophisticated controller architecture than does JavaServer Faces technology. Struts is more sophisticated partly because the application developer can access the controller by creating an Action object that can integrate with the controller, whereas JavaServer Faces technology does not allow access to the controller.
In addition, the Struts controller can do things like access control on each Action based on user roles. This functionality is not provided by JavaServer Faces technology.
Struts frameworks is  better for “web sites”, site like this one, sites that focus on delivering content to the user. Where it’s mostly a “read only” experience for the end user who is likely to want to bookmark things, come back to arbitrarily deep pages, etc.
JSF framework is better for CRUD screens, back office applications, lots of forms and controls, etc. Here, the workflow is more controlled. You tend to not get to a “detail” screen with going through the “list” screen or “header” screen first, for example.
struts validate full beans (validator.xml) jsf has a pluggable validator-mechanism

Advantages of JSF


The major benefits of JavaServer Faces (JSF) technology are:

  1. JavaServer Faces architecture makes it easy for the developers to use. In JavaServer Faces technology, user interfaces can be created easily with its built-in UI component library, which handles most of the complexities of user interface management.
  2. Offers a clean separation between behavior and presentation.
  3. Provides a rich architecture for managing component state, processing component data, validating user input, and handling events.
  4. Robust event handling mechanism.
  5. Events easily tied to server-side code.
  6. Render kit support for different clients
  7. Component-level control over statefulness
  8. Highly ‘pluggable’ – components, view handler, etc
  9. JSF also supports internationalization and accessibility
  10. Offers multiple, standardized vendor implementations

Available implementations and Plugins of JSF?


JSF is the java specification given by the sun microsystems. For this specifications there are multiple;e implementations from the different third party vendors.  The main implementations of JavaServer Faces are:

  1. Reference Implementation (RI) by Sun Micro systems.
  2. Apache MyFaces is an open source JavaServer Faces (JSF) implementation or run-time.
  3. ADF Faces is Oracle’s implementation for the JSF standard.

The main Pluginsof JavaServer Faces are:

  1. Ice Faces FROM ICEsoft Technologies Inc.
  2. Prime Faces from Prime Technology.
  3. Rich Faces from JBoss
  4. Open Faces from TeamDevLtd
  5. DOJO Faces from DOJO

What is JSF?


JSF stands for Java Server Faces and it is an industry standard and a server side user interface component framework for building component-based user interfaces for web applications. JSF has set of pre-assembled User Interface (UI).

It is event-driven programming model. By that it means that JSF has all necessary code for event handling and component organization. Application programmers can concentrate on application logic rather sending effort on these issues. It has component model that enables third-party components to be added like AJAX.

Difference between Iterator and ListIterator


Iterator:

Using Iterator we can iterate only in forward direction and you cannot add elements while iterating and Here cursor always points to specific index.

Example:

 
public class Example {

  public static void main(String[] args) {

    ArrayList aList = new ArrayList();

    aList.add("1");
    aList.add("2");
    aList.add("3");
    aList.add("4");
    aList.add("5");

    Iterator itr = aList.iterator();

    while(itr.hasNext())
      System.out.println(itr.next());

  }
}


ListIterator:

Allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator’s current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().

Example:

public class sample {

  public static void main(String[] args) {
    //create an object of ArrayList
    ArrayList aList = new ArrayList();

    //Add elements to ArrayList object
    aList.add("1");
    aList.add("2");
    aList.add("3");
    aList.add("4");
    aList.add("5");

    //Get an object of ListIterator using listIterator() method
    ListIterator listIterator = aList.listIterator();

    System.out.println(" forward direction using ListIterator");
    while(listIterator.hasNext())
      System.out.println(listIterator.next());

    System.out.println("reverse direction using ListIterator");
    while(listIterator.hasPrevious())
      System.out.println(listIterator.previous());

  }
}

try the above code and get back to me :)

Struts MVC


Struts is MVC based framework developed by Apache. Framework generally provides the basic functionality for a project. Struts provides the set of Action classes, set of tag-libraries, set of Form beans and etc.

Struts combines the most of the design patterns in to a single framework. Struts implements the Single-ton design pattern, Delegate design pattern, Factory Design pattern, Chain of responsibilities.

Struts is Strongly Model View Controller (MVC)based framework MVC fallows the three tier architecture. The model, view and controllers regarding to the Struts are explained as fallows.

View:

View is used to show something to user. Struts allows to use htmls, jsps as view components. To develop the more friendly views struts provided the set of tag libraries. You can download these libraries from the apache site and you can use those into your view components. The set of tag libraries are

struts-html : These tags are replacement of normal html tags. The struts html tags are binds with the form bean properties.

Ex: <html:text property=”userName” />

tag replaces the normal html tag like

<input type=”text” name=”userName” />

struts-bean : These tags are replacement for the jsp action tags. The bean properties are defined with this tags, you can get the bean properties using struts-bean tags.

Ex: <bean:define id=”tempVar” value=”10” />

Above tag defines a variable as ‘tempVar’ and assign 10 to it as string value.

<bean:write name=”Employee” property=”empId” />

Above tag get the value of empId from the Employee form bean.

Struts-logic: These tags are used to write the logical operations. To validate the if conditions or equals conditions you can use these tags.

Ex: <logic:equal name=”empId” value=”100” >Adimin</logic:equal>

Admin is displayed when the empId equals to 100 only.

To get the for loop type iterations you can use the <logic:iterate /> tag.

struts-nested: To display the group of objects you can use the nested tags.

You can implement most of the functionality of above three tags with the nested tags.

Inplace of <bean:write /> you have <nested:write /> and so on…….

Model:

Business logic and persistence logic (database dependent logic) will be developed in Model. In struts you can use normal Java beans, DTOs, Dos as models. You can develop the Model layer using other tools also. Struts allows to use Hibernate, spring in the model layer.

Controller:

Controller is most important concept in the Struts 1.3. In struts ActionServlet acts as Front controller. Each and every request must passes through the ActionServlet. You can change the ActionServlet functionality by extending ActionServlet to your own class.

RequestProcessor class also acts as the controller to process the request. In struts 1.3 Request processor is the ComposableRequestProcessor. It has processXXX() methods. These methods are controls the execution of action classes, controlling of form beans ..etc.

Actions, Dispatch actions, Action Forms , Validator forms ..etc all are come under the controller.