Tuesday, 23 January 2018

Transaction Management in Spring

          In previous post, explained the CRUD operation of Spring with Hibernate, this article we can discuss about Spring Transaction Management with simple examples.   

        A transaction is a logical unit of work that contains one or more statements. A transaction is an atomic unit. The effects of all the statements in a transaction can be either all committed or all rolled back.

See the below diagram to show the transaction management,



      Transaction management is an important part of enterprise applications to ensure data integrity and consistency.

            The concept of transactions can be described as ACID(Atomicity, Consistency,  Isolation, Durability) property:


  • Atomicity
          Atomicity requires that each transaction is “all or nothing”  which means either the sequence of a transaction is successful or unsuccessful.

       If one part of a transaction fails then entire transaction fails.


  • Consistency
         The database value should be consistent from state to state while any data written to the database for any combination of constraints, cascade, triggers etc.

  • Isolation
            Each transaction must be executed in isolation in concurrent environment to prevent data corruption.

  • Durability
         Once a transaction has been committed, the results of this transaction have to be made permanent even in the event of power loss, crashes, or errors.


Spring supports two types of transaction management:
  • Programmatic Transaction Management
  • Declarative Transaction Management


Programmatic transaction management: 

           Programmatic means you have transaction management code surrounding your business code. This gives extreme flexibility, but is difficult to maintain and, well, boilerplate.

Example:--

onlineBooking() {
T1.start();
     checkAvailability();
T1.Commit();

T2.start();

     selectItems();
payment();
itemConfirmation();
T2.commit();
}

I will discuss this in next upcoming post in details.


Declarative transaction management:

              Transaction management is separated from business code and only annotations or XML based configurations are used to manage the transactions.

I will discuss this in upcoming post in details.

Next:


Spring transaction propagation

         Propagation is the ability to decide how the business methods should be encapsulated in both logical or physical transactions.
  • REQUIRED
       The same transaction, if already exists, will be used in the current bean method execution context
if the transaction does not exist already then a new transaction will be created, if multiple methods configured with REQUIRED behavior then they will share the same transaction.

  • REQUIRES_NEW
      This behavior means a new transaction will always be created irrespective of whether a transaction exists or not each transaction runs independently
  • NESTED
        This behavior makes nested Spring transactions to use the same physical transaction but sets savepoints between nested invocations so inner transactions may also rollback independently of outer transactions.
  • MANDATORY
     This propagation states that an existing opened transaction must already exist. If not an exception will be thrown by the container.
  • NEVER
         This behavior states that an existing opened transaction must not already exist. If a transaction exists an exception will be thrown by the container. This is totally opposite to Mandatory propagation.

  • NOT_SUPPORTED
          The NOT_SUPPORTED behavior will execute outside of the scope of any transaction. If an opened transaction already exists it will be paused.
  • SUPPORTS
           The SUPPORTS behavior will execute in the scope of a transaction if an opened transaction already exists.If there isn't an already opened transaction the method will execute anyway but in a non-transaction way.


Spring transaction isolation level 

                 Isolation level defines how the changes made to some data repository by one transaction affect other simultaneous concurrent transactions, and also how and when that changed data becomes available to other transactions. When we define a transaction using the Spring framework we are also able to configure in which isolation level that same transaction will be executed.
  • READ_UNCOMMITTED 
        This isolation level states that a transaction may read data that  is still uncommitted by other transactions.
  • READ_COMMITTED
        This isolation level states that a transaction can't read data that is not yet committed by other transactions.
  • REPEATABLE_READ
        This isolation level states that if a transaction reads one record from the database multiple times the result of all those reading operations must always be the same.
  • SERIALIZABLE 
          This isolation level is the most restrictive of all isolation levels. Transactions are executed with locking at all levels (read, range and write locking) so they appear as if they were executed in a serialized way.


Related Posts:--
1) What is IOC Container in Spring? Difference between BeanFactory and ApplicationContext
2) Spring MVC with Hibernate CRUD Example
3) Spring Annotations and examples
4) Spring Configuration Metadata (XML, Annotation and Java)
5) Spring @Qualifier Annotation with example
6) What is Autowiring in Spring ? Explain Autowiring modes and limitations with examples

Saturday, 20 January 2018

What are the Core Interfaces of Hibernate framework ?

               Hibernate is an Open source Object Relational Mapping(ORM) framework. It enables developer to develop classes to be persist in an object oriented way including inheritance and the Java collections framework. It can provide high performance because of caching algorithm,  check the advantages of Hiberante over Jdbc  in previous post.
           
             Hibernate can provides different interfaces and classes, but I have listed core interfaces as below,

  • Session interface
  • SessionFactory interface
  • Configuration interface
  • Transaction interface
  • Query and Criteria interfaces


Session interface

        It is a single threaded, short-lived object representing a conversation between the application and the persistent store.

It allows you to create query objects to retrieve persistent objects. It's not thread safe.

Synatx:-

Session session = sessionFactory.openSession();

Example:-


  Session session = factory.openSession();
  Transaction tx = null;

  try {
      tx = session.beginTransaction();
      // do some work
      .....
      tx.commit();
  }

  catch (Exception e) {
      if (tx!=null) tx.rollback();
      e.printStackTrace(); 
  } finally {
      session.close();
  }


SessionFactory interface

        The application obtains session instances from SessionFactory. 
There is typically a single SessionFactory for the whole application created 
during application loading.

Syntax:-
SessionFactory sessionFactory = configuration.buildSessionFactory();

Example:-


package com.adnblog;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil {
 
    public static SessionFactory factory;
 
    private HibernateUtil() {
    }
   
     //making the Hibernate SessionFactory object as singleton
 
    public static synchronized SessionFactory getSessionFactory() {
 
        if (factory == null) {
            factory = new Configuration().configure("hibernate.cfg.xml").
                    buildSessionFactory();
        }
        return factory;
    }
}



Configuration interface

            This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify  the location of hibernate specific mapping documents.

Syntax:--


Configuration configuration = new Configuration();

configuration.configure();



Transaction interface

               This interface abstracts the code from any kind of transaction implementation such as JDBC transaction, JTA Transanction.

Syntax:--


session.beginTransaction();

session.save(user);

session.update(user_payrole);

session.getTransaction().commit();


Query and Criteria interfaces

           This interface allows the user to perform queries and also control the flow of the query execution.

Syntax:--

Wednesday, 17 January 2018

Spring Configuration Metadata (XML, Annotation and Java)

        Spring configuration metadata is to tell Spring container how to initiate, configure, wire and assemble the application specific objects. Spring provides three ways of configuration,

  • XML Based Configuration
  • Annotation Based Configuration
  • Java Based Configuration


XML Based Configuration

        All configurations are in one or multiple XML files.  This is the most complicated way of configuration. Large projects require tedious amount of XML which is difficult to manage.

see below examples,

Address.java,
package com.test;
 
public class Address {
 
    private String address;
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
 
}

Employee.java,
package com.test;
 
public class Employee{
 
    private Address address;
 
    public Address getAddress() {
        return address;
    }
 
    public void setAddress(Address address) {
        this.address = address;
    }
 
}

Configuration file, beans.xml as follows,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 
http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <bean id="address" class="com.test.Address">
        <property name="address" value="XYZZ" />
    </bean>
 
    <bean id="employee" class="com.test.Employee">
         <property name="address" ref="address" />
    </bean>
</beans>



Annotation Based Configuration

           Spring 2.5 introduces annotation-based configuration. We still have to write XML files but just to indicate "component-scan" on the packages of annotated classes. This is the preferred way of Spring Configuration.
           In this, we can enable autowire using <context:annotation-config /> in bean configuration. In bean declaration, you can use @Component and if you need to inject other bean then use @Autowired. Refer this for annotation Spring Annotations.

Address.java,
package com.test;
import org.springframework.stereotype.Component;

@Component
public class Address {
 
    private String address;
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
 
}

Employee.java,
package com.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component 
public class Employee{
 
    @Autowired
    private Address address;
 
    public Address getAddress() {
        return address;
    }
 
    public void setAddress(Address address) {
        this.address = address;
    }
 
}

Configuration file(beans.xml),

<?xml version="1.0" encoding="UTF-8"?> 
 
<beans xmlns = "http://www.springframework.org/schema/beans"      
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      
        xmlns:context="http://www.springframework.org/schema/context"    
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
      
     <context:component-scan base-package="com.test"/>
      
     <context:annotation-config> -->

</beans>



Java Based Configuration 

          Starting with Spring 3.0, a pure-Java means of configuring container was provided. We don't need any XML with this method of configuration. Java Config provides a truly object-oriented mechanism for dependency injection, meaning we can take full advantage of re usability, inheritance and polymorphism in the configuration code.  Application developer has complete control over instantiation and dependency injection here.

You need to use two annotations @Configuration and @Bean to achieve this type of configuration.
It's same as Annotation based configuration, except XML file. In this type, XML configuration is not using instead using Java Class and annotating class with @Configuration.

See below Java config class,

package com.test;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
import com.test.Employee;
 
@Configuration
public class JavaConfig {
 
    @Bean(name="employee")
    public Employee getEmployee(){
        return new Employee();
    }
}

Thank you for visiting blog...

Related Posts:--
1) Spring MVC with Hibernate CRUD Example
2) What is IOC Container in Spring? Difference between BeanFactory and ApplicationContext
3) Spring Annotations and its usage
4) What is Autowiring in Spring ? Explain Autowiring modes and limitations with examples
5) Spring @Qualifier Annotation with example
6) What are different Spring Bean Scopes?

Thursday, 11 January 2018

Spring @Qualifier Annotation with example

         In Previous post, we learned the Autowiring, its modes and limitations. In this, we can discuss about @Qualifier annotation uses and examples.

    The @Qualifier annotation is used to resolve the autowiring conflict, when there are multiple beans of same type. This annotation is used with @Autowired annotation.

      The @Qualifier annotation can be used on any class annotated with @Component or 
on method annotated with @Bean. This annotation can also be applied on constructor 
arguments or method parameters.
  
     If two or more beans of same type declared in the configuration file then autowiring conflict will occur if you use only @Autowired, will throw NoSuchBeanDefinitionException.

See below example,

Student.java,

package com.test;
public class Student {

     private String name;

     public String getName() {
          return name;
     }
     public void setName(String name) {
          this.name = name;
     }
}

Bean.xml

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

<bean
class ="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
        
  <bean id="school" class="com.test.School" >

  <bean id="student1" class="com.test.Student" >
       <property name="name" value="Mahesh" />
  </bean>

  <bean id="student2" class="com.test.Student" >
       <property name="name" value="Rajesh" />
  </bean>

</beans>

School.java,

package com.test;

import org.springframework.beans.factory.annotation.Autowired;

public class School{

     @Autowired
     private Student student;
 
     // other property and setter and getters
}

If you run the above code, it will throw NoSuchBeanDefinitionException  as below,

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [com.test.Student] is defined:
expected single matching bean but found 2: [student1, student2]

Because Spring doesn't know which bean should autowire.

To avoid this confusion or exception, should use @Qualifier annotation.

School.java,
package com.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class School{

        @Autowired
        @Qualifier("student1")
        private Student student;
 
        // other property and setter and getters
}



Related Posts:--
1) What is Autowiring in Spring ? Explain Autowiring modes and limitations with examples
2) What is IOC Container in Spring? Difference between BeanFactory and ApplicationContext
3) Spring MVC with Hibernate CRUD Example
4) Spring Annotations
5) String Interview Questions and Answers

Friday, 5 January 2018

What is Autowiring in Spring ? Explain Autowiring modes and limitations with examples

       In Previous post, we discussed about Spring IOC Containers and differences between them, today we will discuss about Autowiring and it's modes and limitations in Spring.
 
       Usually we provide bean configuration details in the spring bean configuration file  and we also specify the beans that will be injected in other beans using ref attribute.  But Spring framework provides autowiring features too where we don’t need to provide bean injection details explicitly.

        Autowiring is to injects the dependencies without having to specify those explicitly. Spring inspects bean factory contents and establishes relationships amongst collaborating beans.

Spring can provide five modes of Autowiring as follows,

Spring autowiring modes

  • no:

It is default which define no autowiring, set it manually via “ref” attribute.

Ex: Using "ref" attribute

<bean id="chat" class="com.test.Chat">
   <property name="messageType" ref="message">
   </property>
</bean>
<bean id="message" class="com.test.Message" >
</bean>


  • byName:

Auto wiring by property name. If the name of a bean is same as the name of other bean property, auto wire it.

Ex:
 Below code, the name of “message” bean is same with the name of the “chat” bean’s property message. So, Spring will auto wired it via setter method – “setMessage(Message message)”.

<bean class="com.test.Chat" id="chat" autowire="byName">
</bean>
<bean class="com.test.Message" id="message">
</bean>

Chat.java,

public class Chat{

    private Message message;

    // other properties

    public void setMessage(Message message){

       this.message = message;

    }

}


  • byType:

Auto wiring by property data type. If data type of a bean is compatible with the data type of other bean property, auto wire it.

Ex:- Below code, the data type of “message” bean is same with the data type of “chat” bean’s property message. So, Spring will auto wired it via setter method – “setMessage(Message message)”.

Configuration file,

<bean class="com.test.Chat" id="chat" autowire="byType">
</bean>
<bean class="com.test.Message" id="message">
</bean>

Chat.java,

public class Chat{

    private Message message;

    // other properties

    public void setMessage(Message message){

       this.message = message;

    }

}


  • constructor:

byType mode in constructor argument.

 Ex: - In below example, the data type of “chat” bean is same as the constructor argument data type in
“message” bean’s property (Message message), so, Spring auto wired it via constructor method – “public Chat(Message message)”.

<bean class="com.test.Chat" id="chat" autowire="constructor">
</bean>
<bean class="com.test.Message" id="message">
</bean>

Chat.java,

public class Chat{

    private Message message;

    // other properties

    public Chat(Message message){

       this.message = message;

    }

}


  • autodetect:
If a default constructor is found, use “autowired by constructor”; Otherwise, use “autowire by type”.

Limitations with Autowiring:--
  1. Explicit dependencies in constructor-argument and property settings always override autowiring. You cannot autowire simple properties such as primitives, Strings, and Classes.
  2. Overriding possibilities: We can define dependencies using property or constructor-args tag which will always override autowiring.
  3. Primitive data type: We have to define primitive data types String or Integer using property or constructor-args tag.  You cannot autowire these tags.
  4. Confusing Nature: If you have lot of dependency in a program, then it’s hard to find using autowire attribute of bean.

Related Posts:--

Thursday, 4 January 2018

What is IOC Container in Spring? Difference between BeanFactory and ApplicationContext


       The Spring IOC Container is a core of the Spring Framework, It will create the objects, wire them together, configure and manage complete life cycle from creation till destruction.
       The Spring Container uses DI(Dependency Injection) to manage the components that make up an application.

The Container will create the objects, those objects are called as Spring Beans.

       Spring Bean is nothing special, any object in the Spring framework that we initialize through Spring container is called Spring Bean. Any normal Java POJO class can be a Spring Bean if it’s configured to be initialized via container by providing configuration metadata information.

       The container gets its instructions on what objects to instantiate, configure and assemble by reading the configuration metadata provided.  The configuration metadata can be represented either by XML, Java annotations or Java code. The following diagram represents a high-level view of how Spring Container works.

IOC Container in Spring


There are two types of Spring IOC Containers,

  •  BeanFactory Container
  •  ApplicationContext Container


BeanFactory Container:

             BeanFactory is the root interface of Spring IoC container.  It is defined in the org.springframework.beans.factory package. It is the actual representation of the Spring IoC container responsible for containing and managing the Spring beans. The BeanFactory, sources application object, configures them and takes care of assembling the dependencies between objects. One of the most popularly used implementation of BeanFactory is the XMLBeanFactory. The XMLBeanFactory allows the representation of objects and their rich dependencies in terms of XML. The XmlBeanFactory takes XML configuration metadata to create the fully  configured application.

Following is the example of simple hello world application using  XMLBeanFactory.

Beans.xml:-

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<bean id="helloWorld" class="com.src.sample.HelloWorld"> 
    <property name="message" value="Hello World!"/> 
</bean>

       The above XML code shows the contents of the bean xml configuration.  It has a single bean configured that has a single property by the name message.  A default value is set for the property.

Next, HelloWorld.java

 package com.src.sample; 
 public class HelloWorld { 
 
      private String message; 
      
      public void setMessage(String message){ 
           this.message = message; 
      } 
      public void getMessage(){ 
           System.out.println(message);
      } 
 }

The main class i.e HelloWorldMain.java to call the bean.

package com.src.sample; 
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory; 
import org.springframework.core.io.ClassPathResource; 

public class HelloWorldMain {     
     public static void main(String[] args) {           
           XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml")); 
           HelloWorld obj = (HelloWorld) factory.getBean("helloWorld"); 
           obj.getMessage(); 
     } 
}

        In the above program, the XmlBeanFactory loads the metadata XML based on the CLASSPATH variable.  It uses the configuration metadata to load, assemble and dispense the beans upon request.
Finally, a method on the bean (getMessage()) is invoked to get the desired result.

       The BeanFactory is preferred when there are limited resources like mobile devices or applets.
BeanFactory is a subset of ApplicaitonContext and provides lesser functionalities. When we need full capabilities with respect to configuration handling then we go for ApplicationContext.



ApplicationContext Container:--

        ApplicationContext is defined by the org.springframework.context.ApplicationContext interface. This is similar to BeanFactory, in that it can load bean definitions, wire them together and dispense beans upon request. In addition, ApplicationContext can also perform more enterprise functionalities like transaction, AOP, resolving text messages from properties files, and push application events to interested listeners.

    The most popularly used ApplicationContext implementations are:

    • FileSystemXmlApplicationContext       
            This implementation loads the definitions of the beans from an XML file. It is required to provide the full path of the XML bean configuration file to the constructor.


    • ClassPathXmlApplicationContext
          This container loads the definitions of the beans from an XML file.  However, it is not required to provide the full path of the XML file. It does require you to set CLASSPATH properly because this container will look for bean configuration XML file in the specified CLASSPATH.

    • XmlWebApplicationContext
    This container loads the XML file with definitions of all beans from within a web application.


    Following is the one sample example of FileSystemXmlApplicationContext,

    HelloWorldMain.java,

    package com.src.sample; 
    import org.springframework.context.ApplicationContext; 
    import org.springframework.context.support.FileSystemXmlApplicationContext;
    
    
    public class HelloWorldMain {   
         public static void main(String[] args) { 
               ApplicationContext  context = new FileSystemXmlApplicationContext ("C:/Program/workspace/SpringExample/src/Beans.xml"); 
               HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); 
               obj.getMessage(); 
         } 
    }
    


    Difference between BeanFactory and the ApplicationContext:--

            The org.springframework.beans.factory.BeanFactory and the
     org.springframework.context.ApplicationContext interfaces acts as the IoC container. The ApplicationContext interface is built on top of the BeanFactory interface.

            It adds some extra functionality than BeanFactory such as simple integration with Spring’s AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.