Wednesday, May 29, 2013

Marker Interfaces , Serialization and serialVersionUID


Marker Interfaces:

An interface contains only abstract methods where as a marker interface contains no methods at all.

yeah, Marker inerface is an interface which doesn't have anything (variables or methods) in it.

examples:

Some example of Marker interfaces are..

java.io.Serializable,

java.lang.Cloneable,

javax.servlet.SingleThreadModel etc..


Why Marker Interfaces:

As Marker interfaces contains no methods why we need to use marker interfaces..? The answer is to instruct the compiler

A marker interface is used to give instructions to the java compiler. Classes that implement these marker interfaces  indicates their special behaviour to compiler.  

As of Java 1.4 Marker inerfaces exists . From Java 5 onwards, we have the concept of annotations which are used to give instructions to java compiler. So marker interfaces are deprecated later.

For e.g, if we write a class which implement Serializable interface (marker), that means we are giving instruction to compiler such that this class is eligible for serialization.


What is Serialization:

Serialization is the process of making an object to be persisted in a stream and can make that object to be tranferred through the network.

Not clear...

Here is the simple definition..

Writing (storing) an object into a stream (e.g file stream) is called Serialization.


Example:

Create a class SerialObject which implement Serializable interface. We can observe that compiler will show the warning The serializable class SerialObject does not declare a static final serialVersionUID field of type long




What is serialVersionUID:

A serialVersionUID is an unique id used by the compiler while in the process of deserialization.

By using serialVersionUID  compiler will check the class that was already serialized is same or not while deserialising it.

i.e to confirm that the class is same while serializing (writing object into stream) and deserialising (reading object from streams).

If we have not provided the serialVersionUID serialization run time will assume some id to the class.

However, as per JAVA specification it is strongly recommended to declare a serialVersionID which should be a static final of type long to avoid unexpected exceptions like InvalidClassException.

Also it should be a private member so that even it's sub classes can't access it.

Our SerialObject class with serialVersionUID and some properties is as shown.



We have declared transient variables, name and notTrransferable.

Transient Variable:

A transient variable is a variable that can't be transferred through a network or we can say , a variable which can't be serialized. That means, we can't write this variable into streams. 

To limit writing data into streams we will use transient variables in serializable classes.


Serializing :

SerializingApp is the class which is showing the process of serialization ( writing object content into file stream).

To write an object we will take the help of java.io.ObjectOutputStream which will accept java.io.OutputStream as an argument.


If the file is available in the specified location it will use that, otherwise FileoutputStream will create a file with the specified name in the specified location.

writeObject() is used to write the object's content into stream.

If we observe the output in the created file write_here.txt, it will only contain objectName and objectId since the remaining are transient and can't be transferred though a network (can't be serialised).


DeSerializing:

Reading the content from a stream and representing it again in the form of an object is called DeSerialization.

DeserialisngApp is the class which is showing process of reading the object from specified file (deserialization).

To write an object we will take the help of java.io.ObjectInputStream which will accept java.io.InputStream as an argument.


we need to specify the location of the file where we have stored our object (SerialObject) to the FileInputStream.

You can clearly observe that the class (SerialObject) which we have stored in the file stream in serialization is the same as the class which we got in deserialization.

serialVersionUID is used by the run time, to confirm that the class is same in Serialization and Deserialization.





Monday, May 27, 2013

Can we create object to Interface and Abstract class ..?


Yes...(but not directly)

We can create the object to An Interface / Abstract class.

As per the java specification we are not allowed to create object to interface and abstract class directly. But we can do that indirectly with the help of anonymous inner type.

Interface:

An interface is one which contains only abstract methods( methods don't have body).
Any variable declared inside an interface are by default public static final and should be initialised

Syntax:



Abstract Class:

An Abstract class is a class that can contain abstract methods or concrete methods( methods those have body) or both.

Syntax:



What happens when we try to create object:

We have an interface SampleInt which contains an abstract method.




SampleAbs is the abstract class with a concrete method showSampleAbs().




Now we are trying to create object to the above defined interface and abstract class in the class App




So , as the compiler is not allowing us to create the object to interface and abstract class we can say We can't create object to an interface or abstract class directly .


How to create object to interface and abstract class:

We can create the object to interface or abstract class indirectly by using anonymous inner type.

App class shows creating object to SampleInt and SampleAbs.




By providing anonymous inner class to Abstract class or interface we can say they have intantiated indirectly.

We can call showSampleAbs() by using SampleAbs object sampleAbs aswellas we can call sampleIntMethod() defined in interface by using it's instance sampleInt.


Calling methods defined inside anonymous type:


Suppose we have defined some more methods inside the implementation (anonymous class), then we can't call them by using instance since the methods not available at the time of object creation.




Calling the methods that are defined inside anonymous inner type will be as shown. 




Note:

Anonymous inner type is simply providing implementation to the corresponding abstract class / interface. 

So we are able to create object to abstract class and an interface by providing implementation in the form of anonymous inner type.

You can observe the behaviour by practising this code.



Tuesday, May 21, 2013

Hibernate(Object Relational Mapping) and working of hibernate


Hibernate:

Hibernate is one of the commonly used ORM tool to deal with database. Hibernate is a framework (software) to be used in applications that deals with database. 

What is ORM:

ORM refers to Object Relational Mapping i.e, Mapping the java objects with the corresponding relational records in the database.

Advantages over jdbc:

As we have jdbc to deal with database,but  hibernate will have more advantages than jdbc.

--> Use of hibernate will improve the productivity (less amount of code compared to jdbc)

--> Hibernate provides relations like one to one , one to many, many to one and many to many

-->  Hibernate comes with HQL ( hibernate query language), which is database independent. So we can deal with any database without changing the code.

--> If we use hibernate, no need to configure connection pool (c3p connection pool will be bundled with hibernate)

--> Hibernate supports two levels of cache (first level and second level) which improves the performance of the application.

--> In hibernate , exceptions that occur are unchecked exceptions where as in jdbc , checked exceptions will be caught and thrown by try catch.

Note:

According to the hibernate documentation, hibernate may not be the best solution for data centric applications which uses stored procedures for buisiness logic. 

Hibernate gives best result for the applications which have buisiness logic as part of java classes instead of stored procedures.


Hibernate Architecture:


As shown pictorially, java application with hibernate api code will communicate with hibernate software which will connect to the database.

Components of Hibernate:

Hibernate mainly consists of three components. They are

--> Hibernate configuration file

--> Hibernate mapping file

--> Pojo classes

Hibernate Configuration file:

A configuration file is an xml file contains the configuration details like driver class name, url, user name and password to connect with database. It also includes the mapping file information

syntax:


A hibernate application contains one configuration file with one or more mapping (hbm) files.

Hibernate mapping file: 

A mapping file (hbm) shows which table is mapped with which pojo class, and mapping the properties of pojo classes with columns of tables.

syntax: 


A Hibernate application can have one or more mapping files. We can map multiple pojo classes with tables by using <class> .

It's recommended to write seperate hbm (mapping) files for each table and pojo class.

Number of mapping files, pojo classes depends on number of tables in the database.

Pojo class:

A POJO (plain old java object) is a normal java bean with couple of setters, getters and/ or some additional methods.

syntax: 



Sample Hibernate application:

Create a java project HibernateSampleApp , add the hibernate capabilities( hibernate jar's ) to the project build path and as discussed earlier we need to have the following files.

A Hibernate Configuration file.




and Hibernate mapping file Student.hbm.xml


and a pojo class Student.java


Now create a main class SampleHibernateApp with main()



If we run the above application, we can found a table with name student in database with columns id, student_name.

As we have defined an extra property in hibernate.cfg.xml, hbm2ddl.auto will create the tables if not exists.

If it's values is update it will update the table if already exists , otherwise it will create the table in database.

show_sql property will show  the query sent to the database in console.


What's happening when we run the application:

When we run the SampleHibernateApp, hibernate will start execution by creating a Configuration object. Immediately hibernate software will call configure() which is an expensive method.

when configure() got called, hibernate will load the configuration file (hibernate.cfg.xml) into jvm's memory and will check for the properties mentioned.

 As we have defined mapping file information in configuration file, hibernate will also loads the mapping file into jvm memory and checks for the appropriate tables in database. If not exists, if we have given hbm2ddl.auto property, hibernate will create the required tables.

So calling configure() takes so much of time to do all these tasks. That's why hibernate specification says we should call configure() only once through out the life time of a project.

Once we have configuration object we can get SessionFactory object by using buildSessionFactory().

When buildSessionFactory() called, hibernate will try to connect with database with the information already stored in jvm memory ( from cfg and hbm files) and will create some basic queries for inserting, updating, deleting and retrieving and stores those queries in jvm memory.

buildSessionFactory() is also an expensive method since lot of task is going behind. We should call this only once through out the project.

A SessionFactory is an interface which can hold a bunch of Session objects.
Once we got SessionFactory we can get session object by calling openSession() which will get's the connection from database.

beginTransaction() will enable the transactions with database.

When we create object to our pojo class Student, the instance variables were initialised with default values initially (0 for int, null for string /advanced data types).

Calling setters will assign the values that we specified to the student object.

Calling session.save() will not send an insert query to the database. The student object will be associated with session object when we call save(). 

When we call commit() hibernate will check in the first level cache ( which will be created at the time of creating session object ) whether any object is associated (attached) to the session object with some code and will get the class name from object (student.getClass()).

 As hibernate already read the cfg,hbm files and stored in jvm, from that information it will get the table to which it has to send the query.

Finally , hibernate will picks the insert query that was already stored in jvm memory based on some internal registration code and will send that query to the database.

We should close the session so that the connection from the database will be given back.

Note:

Using hibernate in web based applications along with spring explained here