In this tutorial,we will see how we can develop JAX-WS endpoint and client step by step.

Web service Tutorial Content:

    Introduction to web services Web services interview questions SOAP web service introduction RESTful web service introduction Difference between SOAP and REST web services SOAP web service example in java using eclipse JAX-WS web service eclipse tutorial JAX-WS web service deployment on tomcat Create RESTful web service in java(JAX-RS) using jersey RESTful web service JAXRS json example using jersey RESTful web service JAXRS CRUD example using jersey AngularJS RESTful web service JAXRS CRUD example using $http RESTful Web Services (JAX-RS) @QueryParam Example Spring Rest simple example Spring Rest json example Spring Rest xml example Spring Rest CRUD example

Prerequisites:

  1. JDK 1.6
  2. Eclipse IDE

Steps for creating JAX-WS webservice endpoint.

1) Open Eclipse IDE
2) Create java project named "JAXWSServer"


3)Create new package named "org.arpit.javapostsforlearning.webservice"

 4)Create JAXWSService Endpoint Interface.
HelloWorld.java
package org.arpit.javapostsforlearning.webservice;
import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public interface HelloWorld {

 @WebMethod public String helloWorld(String name);
}
5)Create JAXWSService Endpoint implementation class.
HelloWorldImpl.java
package org.arpit.javapostsforlearning.webservice;
import javax.jws.WebService;

@WebService(endpointInterface="org.arpit.javapostsforlearning.webservice.HelloWorld")
public class HelloWorldImpl implements HelloWorld{

 public String helloWorld(String name) {
  return "Hello world from "+name;
 }

}
6) Create Endpoint publisher.
HelloWorldWSPublisher.java
package org.arpit.javapostsforlearning.webservice;
import javax.xml.ws.Endpoint;

public class HelloWorldWSPublisher {
 public static void main(String[] args) {
  Endpoint.publish("http://localhost:8080/WS/HelloWorld",new HelloWorldImpl());
 }
}
Run above program.Your webservice is published.You can check your service wsdl at http://localhost:8080/WS/HelloWorld?wsdl

Steps for creating JAXWS Client


1)Open eclipse and create a new java project JAXWSClient.
3) Now we need to generate the client stubs.So open your command line, and enter the wsimport command:
cd %project_home%/src
wsimport -s . http://localhost:8080/WS/HelloWorld?wsdl
you will find java classes generated and compiled under src->org->arpit->javapostsforlearning->webservice

4) Lets create client class now.
create JAXWSClient.java under src->org.arpit.javapostsforlearning.webservice.client
package org.arpit.javapostsforlearning.webservice.client;
import org.arpit.javapostsforlearning.webservice.HelloWorld;
import org.arpit.javapostsforlearning.webservice.HelloWorldImplService;

public class JAXWSClient {

    /**
     * @author Arpit Mandliya
     */
    public static void main(String[] args) {
        
        HelloWorldImplService helloWorldService = new HelloWorldImplService();
        HelloWorld helloWorld = helloWorldService.getHelloWorldImplPort();
        System.out.println(helloWorld.helloWorld("Arpit"));
    }
}

5) Run above program and you will get following output.
Hello world from Arpit

Congratulation,you have successfully created web service endpoint and client.Now in next post,we will deploy it on Tomcat.

In this post,we will see SOAP web service example.

Web service Tutorial Content:

    Introduction to web services Web services interview questions SOAP web service introduction RESTful web service introduction Difference between SOAP and REST web services SOAP web service example in java using eclipse JAX-WS web service eclipse tutorial JAX-WS web service deployment on tomcat Create RESTful web service in java(JAX-RS) using jersey RESTful web service JAXRS json example using jersey RESTful web service JAXRS CRUD example using jersey AngularJS RESTful web service JAXRS CRUD example using $http RESTful Web Services (JAX-RS) @QueryParam Example Spring Rest simple example Spring Rest json example Spring Rest xml example Spring Rest CRUD example

In this post,we will create hello world SOAP web service example in eclipse.Eclipse provides good API for creating web services.Eclipse will do all work for you-creating WSDL,stub,endpoints etc.
Steps for creating web services in eclipse:

1.Create new dynamic web project and name it "SimpleSOAPExample".
Create dynamic web project in eclipse
 2.Create new package named "org.arpit.javapostsforlearning.webservices"

3.Create a simple java class named "HelloWorld.java"
package org.arpit.javapostsforlearning.webservices;

public class HelloWorld {

    public String sayHelloWorld(String name)
    {
        return "Hello world from "+ name;
    }
}

4.Right click on project->new->web service


 5.Click on next.
Create SOAP web services

In service implementation text box,write fully qualified class name of above created class(HelloWorld.java) and move both above slider to maximum level (i.e. Test service and Test Client level) and click on finish.You are done!!A new project named "SimpleSOAPExampleClient" will be created in your work space.
SOAP web services project structure


6.
Start tomcat server
Click on start server.
7.After clicking start server,eclipse will open test web service API.With this test API,you can test your web service.

Test web service

You are done!!.But to understand more about web services,you need to explore more.You can explore above created "SimpleSOAPExampleClient" and learn more about web services.

Source code :

click to begin
6.2 MB .zip
In next post,you will see JAXWS web service example.


In this post,we will see introduction to SOAP web services.

Web service Tutorial Content:

    Introduction to web services Web services interview questions SOAP web service introduction RESTful web service introduction Difference between SOAP and REST web services SOAP web service example in java using eclipse JAX-WS web service eclipse tutorial JAX-WS web service deployment on tomcat Create RESTful web service in java(JAX-RS) using jersey RESTful web service JAXRS json example using jersey RESTful web service JAXRS CRUD example using jersey AngularJS RESTful web service JAXRS CRUD example using $http RESTful Web Services (JAX-RS) @QueryParam Example Spring Rest simple example Spring Rest json example Spring Rest xml example Spring Rest CRUD example

Simple Object Access Protocol (SOAP) is a standard protocol specification for message exchange based on XML. Communication between the web service and client happens using XML messages.
A simple web service architecture have two components
  • Client
  • Service provider
SOAP web service tutorial

So as in above diagram,how client will communicate to service provider.So in order to communicate client must know some information for e.g.
  • Location of webservices server
  • Functions available,signature and return types of function.
  • Communication protocol
  • Input output formats
Service provider will create a standard XML file which will have all above information.So If this file is given to client then client will be able to access web service. This XML file is called WSDL.

What is WSDL?

WSDL stands for Web Service Description Language. It is an XML file that describes
the technical details of how to implement a web service, more specifically the URI,
port, method names, arguments, and data types. Since WSDL is XML, it is both
human-readable and machine-consumable, which aids in the ability to call and bind to
services dynamically.using this WSDL file we can understand things like,
  •     Port / Endpoint – URL of the web service
  •     Input message format
  •     Output message format
  •     Security protocol that needs to be followed
  •     Which protocol the web service uses

Ways to access web service:

There are two ways to access web service.
  • If Service provider knows client:If service provider knows its client then it will provide its wsdl to client and client will be able to access web service.
SOAP web services direct communication


  • Service provider register its WSDL to UDDI and client can access it from UDDI:UDDI stands for Universal Description, Discovery and Integration.It is a directory service. Web services can register with a UDDI and make themselves available through it for discovery.So following steps are involved.
    1. Service provider registers with UDDI.
    2. Client searches for service in UDDI.
    3. UDDI returns all service providers offering that service.
    4. Client chooses service provider
    5. UDDI returns WSDL of chosen service provider.
    6. Using WSDL of service provider,client accesses web service.
SOAP web services indirect communication using UDDI

In next post,we will see SOAP hello world example in java using eclipse.

In this post, we will see introduction to web services and some jargons of web services.

Web service Tutorial Content:

    Introduction to web services Web services interview questions SOAP web service introduction RESTful web service introduction Difference between SOAP and REST web services SOAP web service example in java using eclipse JAX-WS web service eclipse tutorial JAX-WS web service deployment on tomcat Create RESTful web service in java(JAX-RS) using jersey RESTful web service JAXRS JSON example using jersey RESTful web service JAXRS CRUD example using jersey AngularJS RESTful web service JAXRS CRUD example using $http RESTful Web Services (JAX-RS) @QueryParam Example Spring Rest simple example Spring Rest JSON example Spring ReXMLexample Spring Rest CRUD example

Web service is a way of communication that allows interoperability between different applications on different platforms, for example, a java based application on Windows can communicate with a .Net based one on Linux. The communication can be done through a set of XML messages over HTTP protocol.

Web services are browsers and operating system independent service, which means it can run on any browser without the need of making any changes. Web Services take Web-applications to the Next Level.

The World Wide Web Consortium (W3C) has defined the web services. According to W3C, “Web Services are the message-based design frequently found on the Web and in enterprise software. The Web of Services is based on technologies such as HTTP, XML, SOAP, WSDL, SPARQL, and others.”
Lets say,you are a java developer and  you can publish your functions on internet or lan through java web service so any other developer(lets say .Net developer) can access your function.

You can go through web services interview questions for interview questions on web services.

Why you need to learn web services:

Reuse already developed(old) functionality into new software:

Lets understand with very simple example.Lets say you are developing a finance software for a company on java and you have old .net software which manages salary of employees.So rather then developing new software for employee part, you can use old software and for other parts like infrastructure you can develop your own functionalities.

Usability :

Web Services allow the business logic of many different systems to be exposed over the Web. This gives your applications the freedom to chose the Web Services that they need. Instead of re-inventing the wheel for each client, you need only include additional application-specific business logic on the client-side. This allows you to develop services and/or client-side code using the languages and tools that you want.

Interoperability :

This is the most important benefit of Web Services. Web Services typically work outside of private networks, offering developers a non-proprietary route to their solutions.Web Services also let developers use their preferred programming languages. In addition, thanks to the use of standards-based communications methods, Web Services are virtually platform-independent.

Loosely Coupled:

Each service exists independently of the other services that make up the application. Individual pieces of the application to be modified without impacting unrelated areas.

Ease of Integration:

Data is isolated between applications creating ’silos’. Web Services act as glue between these and enable easier communications within and across organisations.

Deployability :

Web Services are deployed over standard Internet technologies. This makes it possible to deploy Web Services even over the fire wall to servers running on the Internet on the other side of the globe. Also thanks to the use of proven community standards, underlying security (such as SSL) is already built-in.

Some jargons used in Web services:

Simple Object Access Protocol(SOAP):

SOAP is a protocol specification for exchanging structured information in the implementation of Web services in computer networks. It relies on XML as its message format.

Web Service Description Language(WSDL):

WSDL stands for Web Service Description Language. It is an XML file that describes
the technical details of how to implement a web service, more specifically the URI,
port, method names, arguments, and data types. Since WSDL is XML, it is both
human-readable and machine-consumable, which aids in the ability to call and bind to
services dynamically.

Elements of WSDL are:

Description:
It is the root element of a WSDL 2.0 file. It usually contains a set of name space declarations which are used throughout the WSDL file. 

Types:
The WSDL types element describes the data types used by your web service.Data types are usually specified by XML schema.It can be described in any language as long as your web services API supports it.

Binding:
The WSDL binding element describes how your web service is bound to a protocol. In other words, how your web service is accessible. To be accessible, the web service must be reachable using some network protocol. This is called "binding" the web service to the protocol.

Interface:
The WSDL interface element describes the operations supported by your web service.It is similar to methods in programming language.Client can only call one opertion per request.

Service:
It describes the endpoint of your web service. In other words, the address where the web service can be reached.

Endpoint:
The endpoint element describes the address of the web service. The endpoint binding attribute describes what binding element this endpoint uses.i.e. protocol with which you will access web service. The address attribute describes the URI at which you can access the service.

Message:
The message element describes the data being exchanged between the Web service providers and consumers.

Sample WSDL file:
   <?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions targetNamespace="http://webservices.javapostsforlearning.arpit.org" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://webservices.javapostsforlearning.arpit.org" xmlns:intf="http://webservices.javapostsforlearning.arpit.org" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!--WSDL created by Apache Axis version: 1.4
Built on Apr 22, 2006 (06:55:48 PDT)-->
 <wsdl:types>
  <schema elementFormDefault="qualified" targetNamespace="http://webservices.javapostsforlearning.arpit.org" xmlns="http://www.w3.org/2001/XMLSchema">
   <element name="sayHelloWorld">
    <complexType>
     <sequence>
      <element name="name" type="xsd:string"/>
     </sequence>
    </complexType>
   </element>
   <element name="sayHelloWorldResponse">
    <complexType>
     <sequence>
      <element name="sayHelloWorldReturn" type="xsd:string"/>
     </sequence>
    </complexType>
   </element>
  </schema>
 </wsdl:types>
   <wsdl:message name="sayHelloWorldRequest">
      <wsdl:part element="impl:sayHelloWorld" name="parameters"/>
   </wsdl:message>
   <wsdl:message name="sayHelloWorldResponse">
      <wsdl:part element="impl:sayHelloWorldResponse" name="parameters"/>
   </wsdl:message>
   <wsdl:portType name="HelloWorld">
      <wsdl:operation name="sayHelloWorld">
         <wsdl:input message="impl:sayHelloWorldRequest" name="sayHelloWorldRequest"/>
         <wsdl:output message="impl:sayHelloWorldResponse" name="sayHelloWorldResponse"/>
      </wsdl:operation>
   </wsdl:portType>
   <wsdl:binding name="HelloWorldSoapBinding" type="impl:HelloWorld">
      <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
      <wsdl:operation name="sayHelloWorld">
         <wsdlsoap:operation soapAction=""/>
         <wsdl:input name="sayHelloWorldRequest">
            <wsdlsoap:body use="literal"/>
         </wsdl:input>
         <wsdl:output name="sayHelloWorldResponse">
            <wsdlsoap:body use="literal"/>
         </wsdl:output>
      </wsdl:operation>
   </wsdl:binding>
   <wsdl:service name="HelloWorldService">
      <wsdl:port binding="impl:HelloWorldSoapBinding" name="HelloWorld">
         <wsdlsoap:address location="http://localhost:8080/SimpleSOAPExample/services/HelloWorld"/>
      </wsdl:port>
   </wsdl:service>
</wsdl:definitions>
    Universal Description, Discovery and Integration(UDDI):

    UDDI stands for Universal Description, Discovery and Integration.It is a directory service. Web services can register with a UDDI and make themselves available through it for discovery

    Web service design approaches:

    Contract last or Bottom up approach:
    When using contract last approach, you first write your java code then you create web service contract(WSDL) .There are various kinds of tools which can generate WSDL on the basis of java code.
    Contract first or Top Down Approach :
    It  is reverse of contract first.Here you first define web service contract.You define all the elements of WSDL first then after that you create your java logic.

    In previous post,we have seen how to develop JAX-WS web service end point and client.In this post,we will see how we can deploy web service end point to application server.

    Web service Tutorial Content:

      Introduction to web services Web services interview questions SOAP web service introduction RESTful web service introduction Difference between SOAP and REST web services SOAP web service example in java using eclipse JAX-WS web service eclipse tutorial JAX-WS web service deployment on tomcat Create RESTful web service in java(JAX-RS) using jersey RESTful web service JAXRS json example using jersey RESTful web service JAXRS CRUD example using jersey AngularJS RESTful web service JAXRS CRUD example using $http RESTful Web Services (JAX-RS) @QueryParam Example Spring Rest simple example Spring Rest json example Spring Rest xml example Spring Rest CRUD example
    Here we will use tomcat as application server.

    1) Open eclipse.
    2) Create new dynamic web project named "HelloWorldWS"
    3) Create new package named "org.arpit.javapostsforlearning.webservice"

     4) Create JAXWSService Interface.
    HelloWorld.java
    package org.arpit.javapostsforlearning.webservice;
    import javax.jws.WebMethod;
    import javax.jws.WebService;
    
    @WebService
    public interface HelloWorld {
    
     @WebMethod public String helloWorld(String name);
    }
    
    5)Create JAXWSService implementation class.
    HelloWorldImpl.java
    package org.arpit.javapostsforlearning.webservice;
    import javax.jws.WebService;
    
    @WebService(endpointInterface="org.arpit.javapostsforlearning.webservice.HelloWorld")
    public class HelloWorldImpl implements HelloWorld{
    
     public String helloWorld(String name) {
      return "Hello world from "+name;
     }
    
    }
    

    6) Now , you need generate Web Services classes, open your command line, and type :
    /* Now You need do following, 
    1) open command prompt.Go to your eclipse workspace(For example: cd E:/arpit/workspace) 
    2) then go to project(For example if project name is jaxws then "cd jaxws") 
    3) paste following "wsgen -s src -d build/classes -cp build/classes org.arpit.javapostsforlearning.webservice.HelloWorldImpl" then enter */
    cd %project_home%
    wsgen -s src -d build/classes -cp build/classes org.arpit.javapostsforlearning.webservice.HelloworldImpl

    Now we will have two class generated under src/org/arpit/javapostsforlearning/webservice/jaxws

    7)Now you need to create web.xml and put it under /HelloWorldWS/WebContent/WEB-INF/
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                             http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">
         <display-name>HellooWorldWS</display-name>
       <listener>
         <listener-class>
            com.sun.xml.ws.transport.http.servlet.WSServletContextListener
         </listener-class>
       </listener>
       <servlet>
          <servlet-name>HelloWorldWS</servlet-name>
          <servlet-class>
            com.sun.xml.ws.transport.http.servlet.WSServlet
          </servlet-class>
       </servlet>
       <servlet-mapping>
         <servlet-name>HelloWorldWS</servlet-name>
         <url-pattern>/HelloWorldWS</url-pattern>
       </servlet-mapping>
    </web-app>
    we have inserted three things here 1.listner-class 2.servlet 3.servlet-mapping
    8) Now we will add sun-jaxws.xml under HelloWorldWS/WebContent/WEB-INF/.It will have endpoint definition.

    <?xml version="1.0" encoding="UTF-8"?>
    <endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">
      <endpoint
         name="HelloWorldWS"
         implementation="org.arpit.javapostsforlearning.webservice.HelloWorldImpl"
         url-pattern="/HelloWorldWS"/>
    </endpoints> 
    9) We need to download some jaxws jars and put jars under /HelloWorldWS/WebContent/WEB-INF/lib.
    click to begin
    5.93MB .zip

    10) Now export your project as war and put it under your Tomcat webapps folder.
    11) If you have target runtime as none then you can refer configure Apache Tomcat in Eclipse IDE.
    then Run tomcat
    12) Click this URL http://localhost:8080/HelloWorldWS/HelloWorldWS
    If You see web service information page then you are done.
    Source:Download 
    

    This is 2nd part of java Serialization tutorial

    Java Serialization Tutorial:

      Serialization in java Java Serialization interview questions and answers serialversionuid in java serialization externalizable in java Transient keyword in java Difference between Serializable and Externalizable in Java

    serialVersionUID is used to ensure that same class(That was used during Serialization) is loaded during Deserialization.serialVersionUID is used for version control of object.
    If you have used Serialization then You might have seen  serialVersionUID because whenever you implement Serializable interface your IDE will give you warning.

    Serialversionuid Syntax:

    As per java docs
    ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

    serialVersionUID must be Static and final.You can assign any number to it.
    Lets see an example:
    Create Employee.java in src->org.arpit.javapostsforlearning

    1.Employee.java
    package org.arpit.javapostsforlearning;
    import java.io.Serializable;
    public class Employee implements Serializable{
    
             private static final long serialVersionUID = 1L;
    
        int employeeId;
        String employeeName;
        String department;
        
        public int getEmployeeId() {
            return employeeId;
        }
        public void setEmployeeId(int employeeId) {
            this.employeeId = employeeId;
        }
        public String getEmployeeName() {
            return employeeName;
        }
        public void setEmployeeName(String employeeName) {
            this.employeeName = employeeName;
        }
        public String getDepartment() {
            return department;
        }
        public void setDepartment(String department) {
            this.department = department;
        }
    }

    Create SerializeMain.java in src->org.arpit.javapostsforlearning

    2.SerializeMain.java
    package org.arpit.javapostsforlearning;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
     public class SerializeMain {
    
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
    
      Employee emp = new Employee();
      emp.setEmployeeId(101);
      emp.setEmployeeName("Arpit");
      emp.setDepartment("CS");
      try
      {
       FileOutputStream fileOut = new FileOutputStream("employee.ser");
       ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
       outStream.writeObject(emp);
       outStream.close();
       fileOut.close();
      }catch(IOException i)
      {
       i.printStackTrace();
      }
     }
    }
    Create DeserializeMain.java in src->org.arpit.javapostsforlearning
    3.DeserializeMain.java
    package org.arpit.javapostsforlearning;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    
    public class DeserializeMain {
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
      
      Employee emp = null;
           try
           {
              FileInputStream fileIn =new FileInputStream("employee.ser");
              ObjectInputStream in = new ObjectInputStream(fileIn);
              emp = (Employee) in.readObject();
              in.close();
              fileIn.close();
           }catch(IOException i)
           {
              i.printStackTrace();
              return;
           }catch(ClassNotFoundException c)
           {
              System.out.println("Employee class not found");
              c.printStackTrace();
              return;
           }
           System.out.println("Deserialized Employee...");
           System.out.println("Emp id: " + emp.getEmployeeId());
           System.out.println("Name: " + emp.getEmployeeName());
           System.out.println("Department: " + emp.getDepartment());
     }
    }
    

    4.Run it:

    First run SerializeMain.java then DeserializeMain.java and you will get following output:
    Deserialized Employee...
    Emp id: 101
    Name: Arpit
    Department: CS
    So when you run program,it was completed successfully and employee.ser has been created on disk.If you again run DeserializeMain.java,it will again run successfully. Now change value of variable serial to
     private static final long serialVersionUID = 2L;
    
    and if you now run DeserializeMain.java it will give you following error.
    java.io.InvalidClassException: org.arpit.javapostsforlearning.Employee; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
    
    So here during deserialization,we got error.It complained about Serialvesionuid being changed.But how does it know? because serialversionuid is a static variable and we know that "We can not serialize static variables".How does it store  serialversionuid? yes ,there is exception.Inspite of serialversionuid being static,it get serialized.So ObjectOutputStream writes every time to output stream and ObjectInputStream reads it back and if it does not have same values as in current version of class then it throw InvalidClassException.

    Why serialversionuid is required?

    In real time,It is possible that you have serialized a object in a file and you deserialized it after few months on different JVM.In between serialization and deserialization class declaration has been changed.So it is a good idea to maintain version system and serialversionid does exactly same thing.It checks if you are deserializing same object which you have serialized.

    Best Practices:

    Java docs says:
    "the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization".

    So it says you must declare serialVersionUID because it give us more control.for e.g. Default rules for generating serialVersionUID can be too strict in some cases. For example when the visibility of a field changes, the serialVersionUID changes too. or sometimes you just want to forbid deserialization of old serialized object then you can just change serialVersionUID.

    Is this enough?.No,you must not only declare it but also maintain it.So most important part is maintaining  serialVersionUID otherwise every thing will run without any exceptions.You should change serialVersionUID when there is some change in the definition of data stored in the class for example data type of field is changed.

    This is 1st part of java Serialization tutorial

    Java Serialization Tutorial:

      Serialization in java Java Serialization interview questions and answers serialversionuid in java serialization externalizable in java Transient keyword in java Difference between Serializable and Externalizable in Java

    Java provides mechanism called serialization to persists java objects in a form of ordered or sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

    So if we need to serialize any object then it can be read and deserialize it using object's type and other information so we can retrieve original object.

    Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
    ObjectOutputStream has many method for serializing object but commonly used method is
        private void writeObject(ObjectOutputStream os) throws IOException
        { 
            
        }
    
    Similarly ObjectInputStream has
        private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException
        {
            
        }
    

    Need of Serialization?

    Serialization is usually used when there is need to send your data over network or to store in files. By data I mean objects and not text.

    Now the problem is your Network infrastructure and your Hard disk are hardware components that understand bits and bytes but not Java objects.

    Serialization is the translation of Java object's values/states to bytes to send it over network or to save it.On other hand,Deserialization is conversion of byte code to corresponding java objects.

    Concept of serialVersionUID :

    serialVersionUID is used to ensure that same class(That was used during Serialization) is loaded during Deserialization.serialVersionUID is used for version control of object.You can read more at serialVersionUID in java serialization


    For Serialization:
    steps are :
    Lets take an example:
    Create Employee.java in src->org.arpit.javapostsforlearning

    1.Employee.java
    package org.arpit.javapostsforlearning;
    import java.io.Serializable;
    public class Employee implements Serializable{ 
       private static final long serialVersionUID = 1L;    
      int employeeId;
        String employeeName;
        String department;
        
        public int getEmployeeId() {
            return employeeId;
        }
        public void setEmployeeId(int employeeId) {
            this.employeeId = employeeId;
        }
        public String getEmployeeName() {
            return employeeName;
        }
        public void setEmployeeName(String employeeName) {
            this.employeeName = employeeName;
        }
        public String getDepartment() {
            return department;
        }
        public void setDepartment(String department) {
            this.department = department;
        }
    }
    As you can see above,if you want to serialize any class then it must implement Serializable interface which is marker interface.
    Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface
    Create SerializeMain.java in src->org.arpit.javapostsforlearning

    2.SerializeMain.java
    package org.arpit.javapostsforlearning;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
     public class SerializeMain {
    
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
    
      Employee emp = new Employee();
      emp.setEmployeeId(101);
      emp.setEmployeeName("Arpit");
      emp.setDepartment("CS");
      try
      {
       FileOutputStream fileOut = new FileOutputStream("employee.ser");
       ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
       outStream.writeObject(emp);
       outStream.close();
       fileOut.close();
      }catch(IOException i)
      {
       i.printStackTrace();
      }
     }
    }

    For Deserialization:

    Steps are:
    Create DeserializeMain.java in src->org.arpit.javapostsforlearning

    3.DeserializeMain.java
    package org.arpit.javapostsforlearning;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    
    public class DeserializeMain {
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
      
      Employee emp = null;
           try
           {
              FileInputStream fileIn =new FileInputStream("employee.ser");
              ObjectInputStream in = new ObjectInputStream(fileIn);
              emp = (Employee) in.readObject();
              in.close();
              fileIn.close();
           }catch(IOException i)
           {
              i.printStackTrace();
              return;
           }catch(ClassNotFoundException c)
           {
              System.out.println("Employee class not found");
              c.printStackTrace();
              return;
           }
           System.out.println("Deserialized Employee...");
           System.out.println("Emp id: " + emp.getEmployeeId());
           System.out.println("Name: " + emp.getEmployeeName());
           System.out.println("Department: " + emp.getDepartment());
     }
    }

    4.Run it:

    First run SerializeMain.java then DeserializeMain.java and you will get following output:
    Deserialized Employee...
    Emp id: 101
    Name: Arpit
    Department: CS
    So we have serialize an employee object and then deserialized it.It seems very simple but it can be very complex when reference object,inheritance come into the picture.So we will see different cases one by one and how we can apply serialization in different scenarios.

    Case 1-What if an object has a reference to other objects

    We have seen very simple case of serialization,now what if it also a reference to other objects.How will it serialized then? will reference object will also get serialized?.Yes,You don't have to explicitly serialize reference objects.When you serialize any object and if it contain any other object reference then Java serialization serialize that object's entire object graph.
    For example:Lets say,Employee now has reference to address object and Address can have reference to some other object(e.g.Home) then when you serialize Employee object all other reference objects such as address and home will be automatically serialized. Lets create Address class  and add object of Address as a reference to above employee class.

    Employee.java:

    package org.arpit.javapostsforlearning;
    import java.io.Serializable;
    
    public class Employee implements Serializable{ 
    
     private static final long serialVersionUID = 1L;
     int employeeId;
     String employeeName;
     String department;
     Address address;
     
     public int getEmployeeId() {
      return employeeId;
     }
     public void setEmployeeId(int employeeId) {
      this.employeeId = employeeId;
     }
     public String getEmployeeName() {
      return employeeName;
     }
     public void setEmployeeName(String employeeName) {
      this.employeeName = employeeName;
     }
     public String getDepartment() {
      return department;
     }
     public void setDepartment(String department) {
      this.department = department;
     }
     public Address getAddress() {
      return address;
     }
     public void setAddress(Address address) {
      this.address = address;
     }
    }

    Create Address.java in org.arpit.javapostsforlearning
    Address.java:
    package org.arpit.javapostsforlearning;
    public class Address {
    
     int homeNo;
     String street;
     String city;
     public Address(int homeNo, String street, String city) {
      super();
      this.homeNo = homeNo;
      this.street = street;
      this.city = city;
     }
     public int getHomeNo() {
      return homeNo;
     }
     public void setHomeNo(int homeNo) {
      this.homeNo = homeNo;
     }
     public String getStreet() {
      return street;
     }
     public void setStreet(String street) {
      this.street = street;
     }
     public String getCity() {
      return city;
     }
     public void setCity(String city) {
      this.city = city;
     }
    }
    Create SerializeDeserializeMain.java in org.arpit.javapostsforlearning
    SerializeDeserializeMain.java:
    package org.arpit.javapostsforlearning;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    public class SerializeDeserializeMain {
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
    
      Employee emp = new Employee();
      emp.setEmployeeId(101);
      emp.setEmployeeName("Arpit");
      emp.setDepartment("CS");
      Address address=new Address(88,"MG road","Pune");
      emp.setAddress(address);
      //Serialize
      try
      {
       FileOutputStream fileOut = new FileOutputStream("employee.ser");
       ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
       outStream.writeObject(emp);
       outStream.close();
       fileOut.close();
      }catch(IOException i)
      {
       i.printStackTrace();
      }
    
      //Deserialize
      emp = null;
      try
      {
       FileInputStream fileIn =new FileInputStream("employee.ser");
       ObjectInputStream in = new ObjectInputStream(fileIn);
       emp = (Employee) in.readObject();
       in.close();
       fileIn.close();
      }catch(IOException i)
      {
       i.printStackTrace();
       return;
      }catch(ClassNotFoundException c)
      {
       System.out.println("Employee class not found");
       c.printStackTrace();
       return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Emp id: " + emp.getEmployeeId());
      System.out.println("Name: " + emp.getEmployeeName());
      System.out.println("Department: " + emp.getDepartment());
      address=emp.getAddress();
      System.out.println("City :"+address.getCity());
     }
    }
    Run it :
    When you run SerializeDeserializeMain.java.You will get following output

    java.io.NotSerializableException: org.arpit.javapostsforlearning.Address
        at java.io.ObjectOutputStream.writeObject0(Unknown Source)
        at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
        at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
        at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
        at java.io.ObjectOutputStream.writeObject0(Unknown Source)
        at java.io.ObjectOutputStream.writeObject(Unknown Source) 
    We got exception what went wrong.I forgot to mention,Address class must also be serializable.So you have to make Address serializable by implement serialzable interface.

    Address.java:
    import java.io.Serializable;
    
    public class Address implements Serializable{
    
     private static final long serialVersionUID = 1L;
     int homeNo;
     String street;
     String city;
     public Address(int homeNo, String street, String city) {
      super();
      this.homeNo = homeNo;
      this.street = street;
      this.city = city;
     } 
     public int getHomeNo() {
      return homeNo;
     }
     public void setHomeNo(int homeNo) {
      this.homeNo = homeNo;
     }
     public String getStreet() {
      return street;
     }
     public void setStreet(String street) {
      this.street = street;
     }
     public String getCity() {
      return city;
     }
     public void setCity(String city) {
      this.city = city;
     }
    }
    Run again:
    When you run again SerializeDeserializeMain.java.You will get following output

    Deserialized Employee...
    Emp id: 101
    Name: Arpit
    Department: CS
    City :Pune 

    Case 2:What if you don't have access to reference object's source code(e.g you don't have access to above Address class)
    If you don't have access to address class then how will you implement serializable interface in Address class.Is there any alternative to that? yes there is,You can create another class which extends address and make it serialzable but It can fails in many cases:
    • What if class is declared as final
    • What if class have reference to other non serializable object.
    So then how will  you serialize Employee object? so solution is you can make it transient.If you don't want to serialize any field then make it transient.
    transient Address address 
    So after making address transient in Employee class when you run program.You will get nullPointerException because during deserialization address reference will be null

    Case 3:What if you still want to save state of reference object(e.g above address object):
    If you make address transient then during deserialization it will return null.But what if you still want to have same state as when you have serialized address object.Java serialization provides a mechanism such that if you have private methods with particular signature then they will get called during serialization and deserialization so if we provide writeObject and readObject method of employee class and they will be called during serialization and deserialization of Employee object.

    Employee.java:
    package org.arpit.javapostsforlearning;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    
    public class Employee implements Serializable{ 
     private static final long serialVersionUID = 1L;
    
    int employeeId;
     String employeeName;
     String department;
     transient Address address;
    
     public int getEmployeeId() {
      return employeeId;
     }
     public void setEmployeeId(int employeeId) {
      this.employeeId = employeeId;
     }
     public String getEmployeeName() {
      return employeeName;
     }
     public void setEmployeeName(String employeeName) {
      this.employeeName = employeeName;
     }
     public String getDepartment() {
      return department;
     }
     public void setDepartment(String department) {
      this.department = department;
     }
     public Address getAddress() {
      return address;
     }
     public void setAddress(Address address) {
      this.address = address;
     }
    
     private void writeObject(ObjectOutputStream os) throws IOException, ClassNotFoundException
     { 
      try {
       os.defaultWriteObject();
       os.writeInt(address.getHomeNo());
       os.writeObject(address.getStreet());
       os.writeObject(address.getCity());
      } 
      catch (Exception e) 
      { e.printStackTrace(); }
     }
     
     private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException
     {
      try {
       is.defaultReadObject();
       int homeNo=is.readInt();
       String street=(String) is.readObject();
       String city=(String) is.readObject();
       address=new Address(homeNo,street,city);
    
      } catch (Exception e) { e.printStackTrace(); }
     }
    }

    One thing should be kept in mind that ObjectInputStream should read data in same sequence in which we have written data to ObjectOutputStream.
    Create Address.java in org.arpit.javapostsforlearning
    Address.java:
    package org.arpit.javapostsforlearning;
    import java.io.Serializable;
    
    public class Address {
    
     int homeNo;
     String street;
     String city;
     
     
     public Address(int homeNo, String street, String city) {
      super();
      this.homeNo = homeNo;
      this.street = street;
      this.city = city;
     }
     public int getHomeNo() {
      return homeNo;
     }
     public void setHomeNo(int homeNo) {
      this.homeNo = homeNo;
     }
     public String getStreet() {
      return street;
     }
     public void setStreet(String street) {
      this.street = street;
     }
     public String getCity() {
      return city;
     }
     public void setCity(String city) {
      this.city = city;
     }
    }

    Create SerializeDeserializeMain.java in org.arpit.javapostsforlearning
    SerializeDeserializeMain.java:
    package org.arpit.javapostsforlearning;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    public class SerializeDeserializeMain {
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
    
      Employee emp = new Employee();
      emp.setEmployeeId(101);
      emp.setEmployeeName("Arpit");
      emp.setDepartment("CS");
      Address address=new Address(88,"MG road","Pune");
      emp.setAddress(address);
      //Serialize
      try
      {
       FileOutputStream fileOut = new FileOutputStream("employee.ser");
       ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
       outStream.writeObject(emp);
       outStream.close();
       fileOut.close();
      }catch(IOException i)
      {
       i.printStackTrace();
      }
    
      //Deserialize
      emp = null;
      try
      {
       FileInputStream fileIn =new FileInputStream("employee.ser");
       ObjectInputStream in = new ObjectInputStream(fileIn);
       emp = (Employee) in.readObject();
       in.close();
       fileIn.close();
      }catch(IOException i)
      {
       i.printStackTrace();
       return;
      }catch(ClassNotFoundException c)
      {
       System.out.println("Employee class not found");
       c.printStackTrace();
       return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Emp id: " + emp.getEmployeeId());
      System.out.println("Name: " + emp.getEmployeeName());
      System.out.println("Department: " + emp.getDepartment());
      address=emp.getAddress();
      System.out.println("City :"+address.getCity());
     }
    }

    Run it :
    When you run SerializeDeserializeMain.java.You will get following output
    Deserialized Employee...
    Emp id: 101
    Name: Arpit
    Department: CS
    City :Pune

    so now we got same state of address object as it was before serialization.

    Inheritance in Serialization:

    Now we will see how inheritance affects serialization.So there can be muliple cases whether super class is serializable or not.If not then how will you handle that and how it works.Lets see by example.
    We will create Person.java which will be superclass of Employee.


    Case 4: What  if superclass is Serializable?
    If superclass is serialzable then all its subclasses are automatically serializable.

    Case 5:What if superclass is not Serializable?
    If super class is not serializable then we have to handle it quite differently.
    • If superclass is not serializable then it must have no argument constructor.
    Person.java
    package org.arpit.javapostsforlearning;
    public class Person {
     
     String name="default";
     String nationality;
     
     public Person()
     {
      System.out.println("Person:Constructor");
     }
    
     public Person(String name, String nationality) {
      super();
      this.name = name;
      this.nationality = nationality;
     }
     
     public String getName() {
      return name;
     }
    
     public void setName(String name) {
      this.name = name;
     }
    
     public String getNationality() {
      return nationality;
     }
    
     public void setNationality(String nationality) {
      this.nationality = nationality;
     }
    
    }

    Create Employee.java in org.arpit.javapostsforlearning
    Employee.java:
    package org.arpit.javapostsforlearning;
    import java.io.Serializable;
    
    public class Employee extends Person implements Serializable{ 
     private static final long serialVersionUID = 1L;
     int employeeId;
     String department;
     
     public Employee(int employeeId,String name,String department,String nationality)
     {
      super(name,nationality);
      this.employeeId=employeeId;
      this.department=department;
      System.out.println("Employee:Constructor");
     }
     
     public int getEmployeeId() {
      return employeeId;
     }
     public void setEmployeeId(int employeeId) {
      this.employeeId = employeeId;
     }
     
     public String getDepartment() {
      return department;
     }
     public void setDepartment(String department) {
      this.department = department;
     }
    }
    Create SerializeDeserializeMain.java in org.arpit.javapostsforlearning
    SerializeDeserializeMain.java:
    package org.arpit.javapostsforlearning;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    public class SerializeDeserializeMain {
    
     /**
      * @author Arpit Mandliya
      */
     public static void main(String[] args) {
    
      //Serialize
      Employee emp = new Employee(101,"Arpit","CS","Indian");
      System.out.println("Before serializing");
      System.out.println("Emp id: " + emp.getEmployeeId());
      System.out.println("Name: " + emp.getName());
      System.out.println("Department: " + emp.getDepartment());
      System.out.println("Nationality: " + emp.getNationality());
      System.out.println("************");
      System.out.println("Serializing");
      try
      {
       FileOutputStream fileOut = new FileOutputStream("employee.ser");
       ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
       outStream.writeObject(emp);
       outStream.close();
       fileOut.close();
      }catch(IOException i)
      {
       i.printStackTrace();
      }
    
      //Deserialize
      System.out.println("************");
      System.out.println("Deserializing");
      emp = null;
      try
      {
       FileInputStream fileIn =new FileInputStream("employee.ser");
       ObjectInputStream in = new ObjectInputStream(fileIn);
       emp = (Employee) in.readObject();
       in.close();
       fileIn.close();
      }catch(IOException i)
      {
       i.printStackTrace();
       return;
      }catch(ClassNotFoundException c)
      {
       System.out.println("Employee class not found");
       c.printStackTrace();
       return;
      }
      System.out.println("After serializing");
      System.out.println("Emp id: " + emp.getEmployeeId());
      System.out.println("Name: " + emp.getName());
      System.out.println("Department: " + emp.getDepartment());
      System.out.println("Nationality: " + emp.getNationality());
     }
    }

    Run it :
    When you run SerializeDeserializeMain.java.You will get following output
    If superclass is not Serializable then all values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. so here name is inherited from person so during deserialization,name is initialized to default.

    Case 6-What if superclass is Serializable but you don't want subclass to be Serializable
    If you don't want subclass to serializable then you need to implement writeObject() and readObject() method and need to throw NotSerializableException from this methods.

    Case 7-Can you Serialize static variables?
    No,you can't.As you know static variable are at class level not at object level and you serialize a object so you can't serialize static variables.

    Externalizable interface can be used in place of serializable if you want more control over serialization.You can read more about it at Externalizable in java

    Summary:

    • Serialization is the translation of your Java object's values/states to bytes to send it over network or save it.On other hand,Deserialization is conversion of byte code to corresponding java objects.
    • Good thing about Serialization is entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.\
    • If you want to serialize any class then it must implement Serializable interface which is marker interface. 
    • Marker interface in Java is interface with no field or methods or in simple word empty interface in java is called marker interface
    • serialVersionUID is used to ensure that same object(That was used during Serialization) is loaded during Deserialization.serialVersionUID is used for version control of object.
    • When you serialize any object and if it contain any other object reference then Java serialization serialize that object's entire object graph.
    • If you don't want to serialize any field,then make it trasient.
    • If superclass is Serializable then its subclasses are automatically Serializable.
    • If superclass is not Serializable then all values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process.
    • If you don't want subclass to serializable then you need to implement writeObject() and readObject() method and need to throw NotSerializableException from this methods.
    • You can't serialize static variables.

    This is 8 of 8 parts of tutorial series

    Tutorial Content:

      Introduction to hibernate framework Hibernate hello world example in eclipse Hibernate interview questions Hibernate one to one mapping example Hibernate one to many mapping example Hibernate many to many mapping example Hibernate inheritance:Table per class hierarchy Hibernate inheritance:table per subclass Hibernate inheritance:Table per concrete class Difference between openSession and getCurrentSession
    In this tutorial,we will see how to implement inheritance in hibernate.There are 3 ways in which you can implement inheritance in hibernate.In this post,we will see one of them i.e.one table per concrete class.

    Inheritance in hibernate:

    Java is object oriented language and inheritance is one of main functionalities of java.Relation model can implement "is a" and "has a" relationship but hibernate provides us way to implement class hierarchy in a different ways.

    Table per concrete class:

    Lets say we have following class hierarchy.We have shape class as base class and Rectangle and Circle inherit from Shape class.

     In  table per concrete class ,One table will be created for each concrete class..So there table will be created SHAPE,RECTANGLE and CIRCLE and subclass repeats property of parent class.

    As per our class diagram,we will create three classes-Shape.java,Rectangle.java and Circle.java

    1.Shape.java

    This is our root class of entity class hierarchy.
    Create Shape.java in src->org.arpit.javapostsforlearning.

    package org.arpit.javapostsforlearning;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Inheritance;
    import javax.persistence.InheritanceType;
    import javax.persistence.Table;
    
    
    @Entity
    @Table(name="SHAPE")
    @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
    public class Shape {
    
     @Id
     @GeneratedValue(strategy = GenerationType.TABLE)
     @Column(name="Shape_Id")
     int shapeId;
     @Column(name="Shape_Name")
     String shapeName;
      
     public Shape()
     {
      
     }
     public Shape(String shapeName)
     {
      this.shapeName=shapeName;
     }
     //getters and setters
     
    }
    
    Shape is our root class so some annotations needs to be used with root class for implementing inheritance.

    @Inheritance:

    For implementing inheritance in hiberante,@Inheritance annotation is used.It defines inheritance strategy to be implement for entity class hierarchy.For one table per class hierarhcy,we have used Table_Per_Class as inheritance strategy.This annotation is defined at root level or sub hierarchy level where different strategy is to be applied.

    2.Rectangle.java

    This is our child class. Create Rectangle.java in src->org.arpit.javapostsforlearning.
    package org.arpit.javapostsforlearning;import javax.persistence.Column;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    
    @Entity
    @Table(name="RECTANGLE")
    public class Rectangle extends Shape{
    
     @Column(name="Rectangle_Length")
     int length;
     @Column(name="Rectangle_Breadth")
     int breadth;
     // getters and setters
     
     public Rectangle()
     {
      
     }
     
     public Rectangle(String shapeName,int length,int breadth)
     {
      super(shapeName);
      this.length=length;
      this.breadth=breadth;
     }
     
     // getters and setters
    }
    

    3.Circle.java

    This is our second child class.
    Create Circle .java in src->org.arpit.javapostsforlearning.
    package org.arpit.javapostsforlearning;import javax.persistence.Column;import javax.persistence.Column;
    import javax.persistence.Entity;
    
    @Entity
    @Table(name="CIRCLE")
    public class Circle extends Shape{
    
     @Column(name="Circle_Radius")
     int radius;
     
     public Circle()
     {
      
     }
     public Circle(String shapeName,int radius)
     {
      super(shapeName);
      this.radius=radius;
      
     }
     // getters and setters
    }
    
    

    4.Hiberante.cfg.xml:

    Create a file named "hibernate.cfg.xml" in src folder.
    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
    
        <session-factory>
    
            <!-- Database connection settings -->
            <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
            <property name="connection.url">jdbc:sqlserver://localhost:1433;database=UserInfo</property>
            <property name="connection.username">sa</property>
            <property name="connection.password"></property>
    
            <!-- JDBC connection pool (use the built-in) -->
            <property name="connection.pool_size">1</property>
    
            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</property>
    
            <!-- Enable Hibernate's automatic session context management -->
            <property name="current_session_context_class">thread</property>
    
            <!-- Disable the second-level cache  -->
            <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
    
            <!-- Drop and re-create the database schema on startup -->
            <property name="hbm2ddl.auto">create</property>
    
      <mapping class="org.arpit.javapostsforlearning.Shape"></mapping>
      <mapping class="org.arpit.javapostsforlearning.Rectangle"></mapping>
      <mapping class="org.arpit.javapostsforlearning.Circle"></mapping>
    
        </session-factory>
    
    </hibernate-configuration>
    
    

    5.Main Class:

    package org.arpit.javapostsforlearning;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.service.ServiceRegistry;
    import org.hibernate.service.ServiceRegistryBuilder;
    
    public class HibernateMain {
    
     public static void main(String[] args) {
      
      Shape shape=new Shape("Sqaure");
      Rectangle rectangle=new Rectangle("Rectangle", 10, 20);  
      Circle circle=new Circle("Circle", 4);
        
      Configuration configuration=new Configuration();
      configuration.configure();
      ServiceRegistry sr= new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
      SessionFactory sf=configuration.buildSessionFactory(sr);
      Session ss=sf.openSession();
      
      ss.beginTransaction();
      ss.save(shape);
      ss.save(rectangle);
      ss.save(circle);
      ss.getTransaction().commit();
      ss.close();
      
     }
    }

    Project Structure:

     

    6.Run it:

    When you run it,you will get following output.

    Hibernate: create table Circle (Shape_Id int not null, Shape_Name varchar(255), Circle_Radius int, primary key (Shape_Id))
    Hibernate: create table Rectangle (Shape_Id int not null, Shape_Name varchar(255), Rectangle_Breadth int, Rectangle_Length int, primary key (Shape_Id))
    Hibernate: create table SHAPE (Shape_Id int not null, Shape_Name varchar(255), primary key (Shape_Id))
    Hibernate: create table hibernate_sequences ( sequence_name varchar(255),  sequence_next_hi_value int ) 
    Feb 05, 2013 11:17:13 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
    INFO: HHH000230: Schema export complete
    Hibernate: select sequence_next_hi_value from hibernate_sequences with (updlock, rowlock ) where sequence_name = 'SHAPE'
    Hibernate: insert into hibernate_sequences(sequence_name, sequence_next_hi_value) values('SHAPE', ?)
    Hibernate: update hibernate_sequences set sequence_next_hi_value = ? where sequence_next_hi_value = ? and sequence_name = 'SHAPE'
    Hibernate: insert into SHAPE (Shape_Name, Shape_Id) values (?, ?)
    Hibernate: insert into Rectangle (Shape_Name, Rectangle_Breadth, Rectangle_Length, Shape_Id) values (?, ?, ?, ?)
    Hibernate: insert into Circle (Shape_Name, Circle_Radius, Shape_Id) values (?, ?, ?)


    7.SQL output:

    SHAPE table in database.




    Rectangle table in database




    CIRCLE table in database





    This is 7 of 8 parts of tutorial series

    Tutorial Content:

      Introduction to hibernate framework Hibernate hello world example in eclipse Hibernate interview questions Hibernate one to one mapping example Hibernate one to many mapping example Hibernate many to many mapping example Hibernate inheritance:Table per class hierarchy Hibernate inheritance:table per subclass Hibernate inheritance:Table per concrete class Difference between openSession and getCurrentSession
    In this tutorial,we will see how to implement inheritance in hibernate.There are 3 ways in which you can implement inheritance in hibernate.In this post,we will see one of them i.e.one table per concrete class.

    Inheritance in hibernate:

    Java is object oriented language and inheritance is one of main functionalities of java.Relation model can implement "is a" and "has a" relationship but hibernate provides us way to implement class hierarchy in a different ways.

    Table per concrete class:

    Lets say we have following class hierarchy.We have shape class as base class and Rectangle and Circle inherit from Shape class.


     In  table per concrete class ,One table will be created for each concrete class..So there table will be created SHAPE,RECTANGLE and CIRCLE and subclass repeats property of parent class.

    As per our class diagram,we will create three classes-Shape.java,Rectangle.java and Circle.java

    1.Shape.java

    This is our root class of entity class hierarchy.
    Create Shape.java in src->org.arpit.javapostsforlearning.

    package org.arpit.javapostsforlearning;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Inheritance;
    import javax.persistence.InheritanceType;
    import javax.persistence.Table;
    
    
    @Entity
    @Table(name="SHAPE")
    @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
    public class Shape {
    
     @Id
     @GeneratedValue(strategy = GenerationType.TABLE)
     @Column(name="Shape_Id")
     int shapeId;
     @Column(name="Shape_Name")
     String shapeName;
      
     public Shape()
     {
      
     }
     public Shape(String shapeName)
     {
      this.shapeName=shapeName;
     }
     //getters and setters
     
    }
    

    Shape is our root class so some annotations needs to be used with root class for implementing inheritance.

    @Inheritance:

    For implementing inheritance in hiberante,@Inheritance annotation is used.It defines inheritance strategy to be implement for entity class hierarchy.For one table per class hierarhcy,we have used Table_Per_Class as inheritance strategy.This annotation is defined at root level or sub hierarchy level where different strategy is to be applied.

    2.Rectangle.java

    This is our child class.
    Create Rectangle.java in src->org.arpit.javapostsforlearning.

    package org.arpit.javapostsforlearning;import javax.persistence.Column;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    
    @Entity
    @Table(name="RECTANGLE")
    public class Rectangle extends Shape{
    
     @Column(name="Rectangle_Length")
     int length;
     @Column(name="Rectangle_Breadth")
     int breadth;
     // getters and setters
     
     public Rectangle()
     {
      
     }
     
     public Rectangle(String shapeName,int length,int breadth)
     {
      super(shapeName);
      this.length=length;
      this.breadth=breadth;
     }
     
     // getters and setters
    }
    

    3.Circle.java

    This is our second child class.
    Create Circle .java in src->org.arpit.javapostsforlearning.
    package org.arpit.javapostsforlearning;import javax.persistence.Column;import javax.persistence.Column;
    import javax.persistence.Entity;
    
    @Entity
    @Table(name="CIRCLE")
    public class Circle extends Shape{
    
     @Column(name="Circle_Radius")
     int radius;
     
     public Circle()
     {
      
     }
     public Circle(String shapeName,int radius)
     {
      super(shapeName);
      this.radius=radius;
      
     }
     // getters and setters
    }
    
    

    4.Hiberante.cfg.xml:

    Create a file named "hibernate.cfg.xml" in src folder.
    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
    
        <session-factory>
    
            <!-- Database connection settings -->
            <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
            <property name="connection.url">jdbc:sqlserver://localhost:1433;database=UserInfo</property>
            <property name="connection.username">sa</property>
            <property name="connection.password"></property>
    
            <!-- JDBC connection pool (use the built-in) -->
            <property name="connection.pool_size">1</property>
    
            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</property>
    
            <!-- Enable Hibernate's automatic session context management -->
            <property name="current_session_context_class">thread</property>
    
            <!-- Disable the second-level cache  -->
            <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
    
            <!-- Drop and re-create the database schema on startup -->
            <property name="hbm2ddl.auto">create</property>
    
      <mapping class="org.arpit.javapostsforlearning.Shape"></mapping>
      <mapping class="org.arpit.javapostsforlearning.Rectangle"></mapping>
      <mapping class="org.arpit.javapostsforlearning.Circle"></mapping>
    
        </session-factory>
    
    </hibernate-configuration>
    
    

    5.Main Class:

    package org.arpit.javapostsforlearning;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.service.ServiceRegistry;
    import org.hibernate.service.ServiceRegistryBuilder;
    
    public class HibernateMain {
    
     public static void main(String[] args) {
      
      Shape shape=new Shape("Sqaure");
      Rectangle rectangle=new Rectangle("Rectangle", 10, 20);  
      Circle circle=new Circle("Circle", 4);
        
      Configuration configuration=new Configuration();
      configuration.configure();
      ServiceRegistry sr= new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
      SessionFactory sf=configuration.buildSessionFactory(sr);
      Session ss=sf.openSession();
      
      ss.beginTransaction();
      ss.save(shape);
      ss.save(rectangle);
      ss.save(circle);
      ss.getTransaction().commit();
      ss.close();
      
     }
    }

    Project Structure:

     

    6.Run it:

    When you run it,you will get following output.

    Hibernate: create table Circle (Shape_Id int not null, Shape_Name varchar(255), Circle_Radius int, primary key (Shape_Id))
    Hibernate: create table Rectangle (Shape_Id int not null, Shape_Name varchar(255), Rectangle_Breadth int, Rectangle_Length int, primary key (Shape_Id))
    Hibernate: create table SHAPE (Shape_Id int not null, Shape_Name varchar(255), primary key (Shape_Id))
    Hibernate: create table hibernate_sequences ( sequence_name varchar(255),  sequence_next_hi_value int ) 
    Feb 05, 2013 11:17:13 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
    INFO: HHH000230: Schema export complete
    Hibernate: select sequence_next_hi_value from hibernate_sequences with (updlock, rowlock ) where sequence_name = 'SHAPE'
    Hibernate: insert into hibernate_sequences(sequence_name, sequence_next_hi_value) values('SHAPE', ?)
    Hibernate: update hibernate_sequences set sequence_next_hi_value = ? where sequence_next_hi_value = ? and sequence_name = 'SHAPE'
    Hibernate: insert into SHAPE (Shape_Name, Shape_Id) values (?, ?)
    Hibernate: insert into Rectangle (Shape_Name, Rectangle_Breadth, Rectangle_Length, Shape_Id) values (?, ?, ?, ?)
    Hibernate: insert into Circle (Shape_Name, Circle_Radius, Shape_Id) values (?, ?, ?)


    7.SQL output:

    SHAPE table in database.





    Rectangle table in database




    Circle table in database
     

    Java tutorial for beginners Copyright © 2012