Sunday, February 22, 2015

Cloning Objects in Java

In Java, objects are manipulated through reference variables, and there is no operator for copying an object—the assignment operator duplicates the reference, not the object. The clone() method provides this missing functionality. In this article, we look into the basic of cloning in Java and types of cloning such as shallow and deep cloning. Also, it disadvantages  and  what are the alternative approach to do the cloning in Java.

Java does not provide an automatic mechanism to clone (make a copy) an object. Recall that when you assign a reference variable to another reference variable, only the reference of the object is copied, not the content of the object. 
Cloning an object means copying the content of the object bit by bit. If you want objects of your class to be cloned, you must re-implement the clone() method in your class. Once you re-implement the clone() method, you should be able to clone objects of your class by calling the clone() method. The declaration of the clone() method in the Object class is as follows:

protected Object clone() throws CloneNotSupportedException

You need to observe few things about the declaration of the clone() method.

  • It is declared protected. Therefore, you will not be able to call it from the client code. The following code is not valid:Object obj = new Object();Object clone = obj.clone(); // Error. Cannot access protected clone() method.This means you need to declare the clone() method public in your class if you want the client code to clone objects of your class.
  • Its return type is Object. It means you will need to cast the returned value of the clone() method. Suppose MyClass is Cloneable. Your cloning code will look as
    MyClass mc = new MyClass();
    MyClass clone = (MyClass)mc.clone(); // Need to use a cast

You do not need to know any internal details about an object to clone it. The clone() method in the Object class has all the code that is needed to clone an object. All you need is to call it from the clone() method of your class. It will make a bitwise copy of the original object and return the reference of the copy.
The clone() method in the Object class throws a CloneNotSupportedException . It means when you call the clone() method of the Object class, you need to place the call in a try-catch block, or re-throw the exception.You have the option not to throw a CloneNotSupportedException from the clone() method of your class

The following snippet of code is placed inside the clone() method of your class, which calls the clone() method of the Object class using the super keyword:
One important thing that you must do is add an "implements Cloneable" clause in your class declaration. Cloneable is an interface declared in the java.lang package.Otherwise, you will get a runtime error when you call the clone() method on the objects of your class.


Once your class implements the clone() method correctly, cloning an object of your class is as simple as calling its clone() method
At this point, there are two separate objects of the Burger class. The veg variable references the original object and vegClone variable references the clone of the original object. The original as well as the cloned object hold the same value of 100. However, they have separate copies of the value. If you change the value in the original object, for example, vegClone.setBurgerPrice(200), the value in the cloned object remains unchanged. Let see the tester class
From Java 5, you need not specify the return type of the clone() method in your class as the Object type. You can specify your class as the return type in the clone() method declaration. This will not force the client code to use a cast when it call the clone() method of your class.
With the above declaration for the clone() method, you can write code to clone an object as follows. Note that no cast is needed anymore

The standard pattern for making a class cloneable is:
  1. Implement Cloneable
  2. Override the clone() method and make it public
  3. In clone() call super.clone() and then copy any mutable object's state
You should not create a new object using new. The proper way is to call super.clone() for a new instance. Object's clone() is special and will create a new copy of the object and copy its primitive fields and references.

Shallow Cloning
An object may be composed of another object. In such cases, two objects exist in memory separately—a contained object and a container object. The container object stores the reference of the contained object. When you clone the container object, the reference of the contained object is cloned. After cloning is performed, there are two copies of the container object; both of them have references to the same contained object. This is called a shallow cloning because references are copied, not the objects. The clone() method of the Object class makes only shallow cloning, unless you code it otherwise.

Example ShallowClone 

An object of the ShallowClone class is composed of an object of the Burger class. The code in the clone() method of the ShallowClone class is the same as for the clone() method of the Burger class. The difference lies in the type of instance variables that are used for the two classes. The Burger class has an instance variable of primitive type int, whereas the ShallowClone class has an instance variable of the reference type DoubleHolder. When the ShallowClone class calls the clone() method of the Object class (using super.clone()), it receives a shallow copy of itself. That is, it shares the Burger object used in its instance variable with its clone.

Following code test an object of the ShallowClone class and its clone. The output shows that after you make a clone, changing the value through the original object also changes the value in the cloned object. This is so because the ShallowClone object stores the value in another object of the Burger class, which is shared by both the cloned and the original objects.

Deep Cloning
When the contained objects are copied rather than their references during cloning of a compound object, it is called deep cloning. You must clone all the objects referenced by all reference variables of an object to get a deep cloning.
A compound object may have multiple levels of chaining of contained objects. For example, the container object may have a reference of another contained object, which in turn has a reference of another contained object and so on. Whether you will be able to perform a deep cloning of a compound object depends on many factors. If you have a reference of a contained object, it may not support cloning and in that case, you have to be content with shallow cloning. You may have a reference of a contained object, which itself is a compound object. However, the contained object supports only shallow cloning, and in that case again, you will have to be content with shallow cloning.

In a deep cloning, you need to clone all objects referenced by all reference instance variables of an object. You must perform a shallow cloning before you can perform a deep cloning. The shallow cloning is performed by calling the clone() method of the Object class. Then you will need to write code to clone all reference instance variables.

Example DeepClone 

If you compare the code in the clone() method of the ShallowClone and DeepClone classes, you will find that for deep cloning you had to write only one extra line of code.

copy.burger = (Burger)this.burger.clone();

What will happen if the Burger class is not cleanable? In that case, you would not be able to write the above statement to clone the holder instance variable. You could have cloned the burger instance variable as follows:

copy.burger = new Burger(this.burger.getValue());

The goal is to clone the burger instance variable and it does not have to be done by calling its clone() method

Clone Method
In order for implementing the Cloneable interface to have any effect on a class, it and all of its superclasses must obey a fairly complex, unenforceable, and largely undocumented protocol. It creates an object without calling a constructor. The general contract for the clone method is weak. Here it is, copied from the specification for java.lang.Object:

Using the clone() method of the Object class is not the only way to make a clone of an object. You can use other methods to clone an object. You may provide a copy constructor, which accepts an object of the same class and creates a clone of that object. You may provide a factory method in your class, which may accept an object and returns its clone. Another way to clone an object is to serialize it and then deserialized it.

The copy constructor approach and its static factory variant have many advantages over Cloneable/clone:

  • They do not rely on a risk-prone extralinguistic object creation mechanism Where as in clonealbe, In order for implementing the Cloneable interface to have any effect on a class, it and all of its superclasses must obey a fairly complex, unenforceable, and largely undocumented protocol. The resulting mechanism is extralinguistic: It creates an object without calling a constructor.
  • They do not conflict with the proper use of final fields where in cloneable, If a class is not final, `clone` has to return the most derived class for which it was called. That can't work with a constructor, because `clone` doesn't know which one to call. If a class is final, it can't have any subclasses, so there's no danger in calling its constructor when cloning.
  • They do not require the client to catch an unnecessary checked exception, where it require clonealbe require the client to handle the exception.
  • They provide a statically typed object to the client.

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Thursday, February 5, 2015

Assertions in Java

When creating application programs, you assume many things. However, often it happens that the assumptions don’t hold, resulting in an erroneous condition. The assert statement is used to check or test your assumptions about the program. In this article, we try to understand how and when to use assert keyword in Java.

There are many reasons why you should add assertions to the program. One reason is that it helps find the problems early; when you check your assumptions in the program, and when any of them fail, you immediately know where to look out for the problem and what to fix. Also, when other programmers read your code with assertions, they will be in a better position to understand the code because you are making your assumptions explicit using assertions.

The keyword assert provides support for assertions in Java. Each assertion statement contains a Boolean expression

  • If the result of the Boolean expression is true, it means the assumption is true, nothing happens. 
  • However, if the Boolean result is false, then the assumption you had about the program holds no more, and an AssertionError is thrown. 

Remember that the Error class and its derived classes indicate serious runtime errors and are not meant to be handled. In the same way, if an AssertionError is thrown, the best course of action is not to catch the exception and to allow the program to terminate. After that, you need to examine why the assumption did not hold true and then fix the program.

A simple assertion is a statement of the form:

assert logical_expression;

Here, assert is a keyword, and logical_expression is any expression that results in a value of true or false . When this statement executes, if logical_expression evaluates to true , then the program continues normally. If logical_expression evaluates to false , the program is terminated with an error message starting with: java.lang.AssertionError. This is followed by more information about where the error occurred in the code. When this occurs, the program is said to assert.

Assert Statement
Assert statements in Java are of two forms:

  • assert booleanExpression;
  • assert booleanExpression : "Detailed error message string";

It is a compiler error if a non-Boolean expression is used within the assert statement.

In this program, you are checking if the value of i is < 0; you are using the expression –i to convert it to a positive value. Once the condition check if (i < 0) is completed, the value of i cannot be negative, or that is your assumption. Such assumptions can be asserted with an assert statement.
The program will run fine if the Boolean expression (i >= 0) evaluates to true. However, if it evaluates to false, the program will crash by throwing an AssertionError.
Yes, this program executed successfully without throwing any exceptions.

Is there any value of i for which the condition will fail? Yes, there is! If the value of i is a minimum possible value of integer, then it cannot be converted into a positive value. Why? Remember that the range of integers is -2^31 to 2^31 – 1, so the integer values the value of i as –2147483648 to 2147483647. In other words, the positive value 2147483648 is not in the range of integers. So, if the value of i is –2147483648, then the expression -i will overflow and again result in the value –2147483648. Thus, your assumption is not true.

int i = Integer.MIN_VALUE;


Enable/Disable Assertion
You saw that assertions are disabled at runtime; to enable assertions at runtime, use an -ea switch.To disable assertions at runtime, use a -da switch. If assertions are disabled by default at runtime, then what is the use of -da switch? There are many uses. For example, if you want to enable assertions for all classes within a given package and want to disable asserts in a specific class in that package, then a -da switch is useful.

How Not to Use Asserts
The key to understanding assertions is that they are useful for debugging and testing applications, and assertions are meant to be disabled when the application is deployed to end users.

  • Don’t use assertions for validating input values or for validating arguments to public methods. For signaling such runtime failures, use exceptions instead.
  • Don’t use assertions to check conditions that are required for the correct functioning of the application. Since assertions are disabled by default at runtime, the application will not function correctly when the asserted conditions are not present in the code.
  • The Boolean expressions given inside assert statements should not have side effects— modifying variable values, printing values to console, etc. In other words, the functioning of the application should remain the same no matter if assertions are enabled or disabled.

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Friday, December 26, 2014

String pool concept in Java

String pooling (sometimes also called as string canonicalisation) is a process of replacing several String objects with equal value but different identity with a single shared String object. This is the most basic and predominant concept that every Java developer should know. In this article, we understand the concept of pooling with the help of few examples.
You can create objects of the class String by using the new operator, by using the assignment operator ( = ), or by enclosing a value within double quotes ( " ). But you may have noticed a big difference in how these objects are created, stored, and referred by Java.

Let’s create two String objects with the value "JavaLatte" using the operator new :

This image illustrates the previous code.

In the previous code, a comparison of the String reference variables str1 and str2 prints false . The operator == compares the addresses of the objects referred to by the variables str1 and str2 . Even though these String objects store the same sequence of characters, they refer to separate objects that are stored at separate locations.

Let’s create two String objects with the value "Latte" using the assignment operator ( = ). 
The variables str3 and str4 and the objects referred to by these variables
In the previous example, the variables str1 and str2 referred to different String objects, even if they were created using the same sequence of characters. In the case of variables str3 and str4, the objects are created and stored in a pool of String objects. Before creating a new object in the pool, Java first searches for an object with similar contents.

When the following line of code executes, no String object with the value "Latte" is found in the pool of String objects:
String str3 = "Latte";
As a result, Java creates a String object with the value "Latte" in the pool of String objects referred to by variable str3. See the image for understanding this
When the following line of code executes, Java is able to find a String object with the value "Latte" in the pool of String objects:
String str4 = "Latte";

Java doesn’t create a new String object in this case, and the variable str4 refers to the existing String object "Latte".

You can also create a String object by enclosing a value within double quotes ( " ):

These values are reused from the String constant pool if a matching value is found. If a matching value isn’t found, the JVM creates a String object with the specified value and places it in the String constant pool:

Compare the preceding example with the following example, which creates a String object using the operator new and (only) double quotes and then compares their references:

The preceding code shows that object references of String objects that exist in the String constant pool and object references of String objects that don’t exist in the String constant pool don’t refer to the same String object, even if they define the same String value.

Where String pool is stored in memory

  • Java 6
    Permanent Generation part of the heap structure - the fixed size part of heap mainly used for storing loaded classes and string pool. Note that the permanent generation is not part of the heap. It's a separate space for class definitions and related data, as well as where interned strings live

  • Java 7
    The string pool was relocated to the heap. It means that you are no longer limited by a separate fixed size memory area. All strings are now located in the heap, as most of other ordinary objects, which allows you to manage only the heap size while tuning your application
Note strings in the JVM string pool are eligible for garbage collection if there are no references to them from your program roots. It means that if your interned string went out of scope and there are no other references to it – it will be garbage collected from the JVM string pool.

Use of String intern() method
Returns a canonical representation for the string object.

A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned.

String allocation, like any other object creation proves costly in time and memory.The JVM do some trickery while instantiating the string literals to increase performance and decrease memory overhead. To decease the number of creation of String object in JVM, the String class keeps a pool of Strings. Each time you create a string literal, the JVM checks the string literal pool first. If a string is found in the pool, a reference to the pooled string is return.if the String is not exist in the pool, a new string object is instantiates, then placed in the pool.

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Monday, December 22, 2014

ClassCastException in Java

ClassCastException exception is thrown when an attempt is made to cast between incompatible types (such as String to Integer type or vice versa).  In this article, we understand this exception in more detail and find out the way to avoid this exception with examples.

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:
Object x = new Integer(0);

Take a look at the above figure to review the class hierarchy of this exception. Examine the code where the line of code that throws the ClassCastException is shown in bold.

ClassCastException is thrown when an object fails an IS-A test with the class type to which it’s being cast. In the preceding example, class Ink is the base class for classes ColorInk and BlackInk. The JVM throws a ClassCastException in the previous case because the line of code in bold tries to explicitly cast an object of ColorInk to BlackInk.

Why above code avoided the compilation error
Note that above line of code avoided the compilation error because the variable inks defines an ArrayList of type Ink , which is capable of storing objects of type Ink and all its subclasses. The code then correctly adds the allowed objects: one each of BlackInk and ColorInk.

If the code had defined an ArrayList of type BlackInk or ColorInk , the code would have failed the compilation, as follows:
Here’s the compilation error thrown by the previously modified piece of code:

How to avoid ClassCastException
If a ClassCastException is thrown while executing a program, and if there are no exception handlers for that, the program will terminate. So, how about providing an exception handler like this?
Yes, this will work and the program will not crash. But this is a really bad idea! There are two main problems in this code.

  • Providing exception handlers for RuntimeExceptions like this create an illusion that the program is working perfectly fine, when it is not!
  • Runtime exceptions like ClassCastException indicate programming errors and should not be caught using exception handlers.
Okay, so what do you do now? Before downcasting, check for the dynamic type of the object and then downcast. You can use the instanceof operator to verify whether an object can be cast to another class before casting it.

This is an effective and proper way to achieve downcasting. Using the instanceof operator checks the dynamic type of obj, which helps you to decide whether to downcast it to a String object.

Continue with our main example. Assuming that the definition of classes Ink , ColorInk, and BlackInk are the same as defined in the previous example, the following lines of code will avoid the ClassCastException

In the previous example, the condition ( inks.get(0)instanceofBlackInk ) evaluates to false , so the then part of the if statement doesn’t execute.

Try to examine and share the output of the following program in comment section

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Sunday, November 23, 2014

Finding superclasses of an object in Java

In this article, we look into one of the mechanism of an Reflection to find about the super classes of any object in Java with example.  Reflection enables what is commonly referred to as dynamic programming in Java. Reflection in Java is accomplished using the Java Reflection API

Reflection is a mechanism for discovering data about a program at run-time. The most basic thing you usually do when doing reflective programming is to get a Class object. Once you have a Class object instance, you can obtain all sorts of information about the class and even manipulate the class.

Finding Superclasses
The ancestors of a given class are referred to as that class’s superclasses. Using reflection, you can determine all of the ancestors of a given class. After you've obtained a Class object, you can use the getSuperclass() method to get the class’s superclass if one exists. If a superclass exists, a Class object will be returned. If there is not a superclass, this method will return null. Remember that Java supports only single inheritance, so for any given class, there can be only one superclass.  Actually to be clear, there can be only one direct superclass.Technically, all ancestor classes are considered to be superclasses of a given class.To retrieve all ancestor superclasses, you would recursively call the getSuperclass() method on each Class object that is returned.

Here is an example, that explain the above concept 

Example 2 In this example, we try to find the super classes of BigDecimal class. 

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Saturday, November 1, 2014

Implicit Objects In JSP

JavaServer Pages (JSP) technology allows you to easily create web content that has both static and dynamic components. JSP technology makes available all the dynamic capabilities of Java Servlet technology but provides a more natural approach to creating static content. In this article, we look into the 9 implicit object of JSP with explanation and examples.

In a web application, multiple web components collaborate with each other and share information by means of objects that are maintained as attributes of four scope objects. You access these attributes by using the getAttribute and setAttribute methods of the class representing the scope

Note In addition to the standard servlet request, session, and application scopes, JSP adds a fourth scope called page scope.

A JSP page can access some specific objects through scripting variables. These objects are provided by the JSP container and are called implicit objects. These implicit objects can be accessed in scriptlets, in expressions, or as part of the EL expressions.

  • application
    The implicit application object provides a reference to the javax.servlet.ServletContext interface. The ServletContext interface is used to provide access to any context-initialization parameters that have been configured for the JSP page via the deployment descriptor of the web application. The ServletContext object and parameters stored in them by the web container are available to the entire web application. The application object provides the developer of the JSP page with access to the ServletContext object.
    In short, application provides access to web context. Its use is similar to that of ServletContext.
  • config
    Similar to the application object, the config object provides a reference to the ServletConfig interface of the web application. The ServletConfig interface is used to provide access to any initialization parameters that have been configured for the JSP page via the deployment descriptor of the web application. The config object provides the JSP developer with access to the ServletConfig object.
    In short, config provides initialization information used by the JSP container. Its use is similar to that of the class ServletConfig.
  • exception
    The implicit exception object is available to JSP to handle the error conditions and report the runtime exceptions using the errorPage page directive. Exception represents an instance of the Throwable object and contains error information. This variable is available only from the JSP error page
  • out
    The implicit out object represents an instance of the JspWriter class that is used to write character data to the response stream. out represents the output write stream JspWriter. This variable points at the same object as HttpServletResponse.getWriter() in servlets. For example, a simplest JSP that returns a result from a Java class called CurrencyConverter might look like this
         <% out.println(CurrencyConverter.getDollarRate()); %>
  • page
    The JSP implicit page object is an instance of the Object class and represents the current JSP page. In short, page represents the instance of the JSP’s servlet.
  • pageContext
    A pageContext provides context information by providing access to all the namespaces associated with a JSP page and to several page attributes. Also, it contains the reference to implicit objects. pageContext represents the JSP context and is used with Tag Libraries
  • request
    The request object is an instance of the javax.servlet.http.HttpServletRequest interface. It represents the client request. The request implicit object is generally used to get request parameters, request attributes, header information, and query string values.
  • response
    The implicit response object is an instance of the javax.servlet.http.HttpServletResponse interface and represents the response to be given to the client. The implicit response object is generally used to set the response content type, add cookies, and redirect the response.
  • session
    The JSP implicit session object is an instance of a Java class that implements the javax.servlet.http.HttpSession interface. It is used to store session state for a client.

Examples of Common Implicit Objects

getServletContext().setAttribute("blog", JavaLatte);
This sets the book attribute in a ServletContext without using implicit objects.

request.setAttribute("blog", JavaLatte);
This sets the book attribute in a request object. The request object is also an implicit object in JSP. Hence, setting the attribute in a servlet is similar to setting the attribute in a JSP page.

request.getSession().setAttribute("book", book);
This sets the book attribute in the session without using implicit objects

application.setAttribute("book" book);
This sets the book attribute in the ServletContext using the application implicit object.

request.setAttribute("book" book);
This sets the book attribute in a request object. request is also an implicit object in JSP. Hence, setting the attribute in JSP is similar to setting the attribute in a servlet.

session.setAttribute("book" book);
This sets the book attribute in the session using a session implicit object

pageContext.setAttribute("book" book);
This sets the book attribute in PageContext using a pageContext implicit object. There is no equivalent of pageContext in a servlet. A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, and provides a layer above the implementation details. Implicit objects are added to the pageContext automatically.

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

Saturday, October 25, 2014

How Hibernate Works and it's Persistence Lifecycle

The main idea behind any ORM framework is to replace writing SQL with manipulating the objects. In the Java world, this means putting a layer on top of JDBC that will enable you to simply create a POJO, assign values to its fields, and tell it “Persist yourself in the database.” This is what Hibernate is for. In this article, we look into overview of how hibernate works and its main components. By going through this, you'll able to answers about hibernate in an interview.

Hibernate's primary feature is mapping from Java classes to database tables (and from Java data types to SQL data types). Hibernate also provides data query and retrieval facilities. It generates SQL calls and relieves the developer from manual result set handling and object conversion. Applications using Hibernate are portable to supported SQL databases with little performance overhead

Hibernate architecture
As you can see from following picture, how much of Hibernate you use depends on your needs. At its simplest level Hibernate provides a lightweight architecture that deals only with ORM. Full-blown usage of Hibernate fully abstracts most aspects of persistence, such as transaction, entity/query caching, and connection pooling.

How Hibernate Works
Hibernate’s success lies in the simplicity of its core concepts. At the heart of every interaction between your code and the database lies the Hibernate Session. Following image provides an overview of how Hibernate works and don't need any explanation if you have an idea about hibernate.

The heart of any Hibernate application is in its configuration. There are two pieces of configuration required in any Hibernate application: one creates the database connections, and the other creates the object-to-table mapping
Let's see the basic introduction to all the component and there roles in hibernate.

Configure the Database Connection (.cfg.xml)
To create a connection to the database, Hibernate must know the details of our database, tables, classes, and other mechanics. This information is ideally provided as an XML file (usually named hibernate.cfg.xml) or as a simple text file with name/value pairs (usually named

In XML style. We name this file hibernate.cfg.xml so the framework can load this file automatically.
The following snippet describes such a configuration file. Because I am using MySQL as the database, the connection details for the MySQL database are declared in this hibernate.cfg.xml file:

The preceding properties can also be expressed as name/value pairs. For example, here’s the same information represented as name/value pairs in a text file titled

hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost:3307/JH
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

connection.url indicates the URL to which we should be connected, driver_class represents the relevant Driver class to make a connection, and the dialect indicates which database dialect we are using (MySQL, in this case). If you are following the file approach, note that all the properties are prefixed with “hibernate” and follow a pattern—hibernate.* properties, for instance

Beyond providing the configuration properties, we also have to provide mapping files and their locations. As mentioned earlier, a mapping file indicates the mapping of object properties to the row column values. This mapping is done in a separate file, usually suffixed with .hbm.xml. We must let Hibernate know our mapping definition files by including an element mapping property in the previous config file, as shown here:

 <mapping resource="table1.hbm.xml" />
 <mapping resource="table2.hbm.xml" />
 <mapping resource="table3.hbm.xml" />

Create Mapping Definitions
Once we have the connection configuration ready, the next step is to prepare the table1.hbm.xml file consisting of object-table mapping definitions. The following XML snippet defines mapping for our Movie object against the TABLE1 table:

 <class name="" table="TABLE1">
 <id name="id" column="ID">
 <generator class="native"/>
 <property name="title" column="TITLE"/>
 <property name="director" column="DIRECTOR"/>
 <property name="synopsis" column="SYNOPSIS"/>


There is a lot going on in this mapping file. The hibernate-mapping element holds all the class-to-table mapping definitions. Individual mappings per object are declare under the class element. The name attribute of the class tag refers to our POJO domain class, while the table attribute refers to the table TABLE1 to which the objects are persisted.
The remaining properties indicate the mapping from the object’s variables to the table’s columns (e.g., the id is mapped to ID, the title to TITLE, director to DIRECTOR, etc.). Each object must have a unique identifier—similar to a primary key on the table. We set this identifier by implementing the id tag using a native strategy.

What does Hibernate do with this properties file?
The Hibernate framework loads this file to create a SessionFactory, which is thread-safe global factory class for creating Sessions. We should ideally create a single SessionFactory and share it across the application. Note that a SessionFactory is defined for one, and only one, database. For instance, if you have another database alongside MySQL, you should define the relevant configuration in hibernate.hbm.xml to create a separate SessionFactory for that database too.

The goal of the SessionFactory is to create Session objects. Session is a gateway to our database. It is the Session’s job to take care of all database operations such as saving, loading, and retrieving records from relevant tables. The framework also maintains at transnational medium around our application. The operations involving the database access are wrapped up in a single unit of work called a transaction. So, all the operations in that transaction are either successful or rolled back.

Keep in mind that the configuration is used to create a Session via a SessionFactory instance. Before we move on, note that Session objects are not thread-safe and therefore should not be shared across different classes.

The Hibernate Session
The Hibernate Session embodies the concept of a persistence service (or persistence manager) that can be used to query and perform insert, update, and delete operations on instances of a class mapped by Hibernate. In an ORM tool you perform all of these interactions using object oriented semantics; that is, you no longer are referring to tables and columns, but you use Java classes and object properties. As its name implies, the Session is a short-lived, lightweight object used as a bridge during a conversation between the application and the database. The Session wraps the underlying JDBC connection or J2EE data source, and it serves as a first-level cache for persistent objects bound to it.

The Session Factory
Hibernate requires that you provide it with the information required to connect to each database being used by an application as well as which classes are mapped to a given database. Each one of these database-specific configuration files, along with the associated class mappings, are compiled and cached by the SessionFactory, which is used to retrieve Hibernate Sessions. The SessionFactory is a heavyweight object that should ideally be created only once (since it is an expensive and slow operation) and made available to the application code that needs to perform persistence operations

Each SessionFactory is configured to work with a certain database platform by using one of the provided Hibernate dialects. The choice of Hibernate dialect is important when it comes to using databasespecific features like native primary key generation schemes or Session locking. At the time of this writing Hibernate (version 3.1) supports 22 database dialects. Each of the dialect implementations are in the package org.hibernate.dialect

The Hibernate Object Mappings
Hibernate specifies how each object state is retrieved and stored in the database via an XML configuration file. Hibernate mappings are loaded at startup and are cached in the SessionFactory. Each mapping specifies a variety of parameters related to the persistence lifecycle of instances of the mapped class such as:

  • Primary key mapping and generation scheme
  • Object-field-to-table-column mappings
  • Associations/Collections
  • Caching settings
  • Custom SQL, store procedure calls, filters, parameterized queries, and more

Persistence Lifecycle of Hibernate
There are three possible states for a Hibernate mapped object. Understanding these states and the actions that cause state transitions will become very important when dealing with the more complex Hibernate problems.

In the transient state, the object is not associated with a database table. That is, its state has not been saved to a table, and the object has no associated database identity (no primary key has been assigned). Objects in the transient state are non-transactional, meaning that they do not participate in the scope of any transaction bound to a Hibernate Session. After a successful invocation of the save or saveOrUpdate methods an object ceases to be transient and becomes persistent. The Session delete method (or a delete query) produces the inverse effect making a persistent object transient.

Persistent objects are objects with database identity. (If they have been assigned a primary key but have not yet been saved to the database, they are referred to as being in the “new” state). Persistent objects are transactional, which means that they participate in transactions associated with the Session (at the end of the transaction the object state will be synchronized with the database).

A persistent object that is no longer in the Session cache (associated with the Session) becomes a detached object. This happens after a transaction completes, when the Session is closed, cleared, or if the object is explicitly evicted from the Session cache. Given Hibernate transparency when it comes to providing persistent services to an object, objects in the detached state can effectively become intertier transfer objects and in certain application architectures can replace the need to have DTOs (Data Transfer Objects).

I believe this has cleared you concept of how hibernate works and its components.

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...