Tuesday, 23 January 2018

A Complete Guide to Spring Transaction Management

           In the previous post, we learned how to perform CRUD operations using Spring and Hibernate. In this article, we will discuss Spring Transaction Management with simple examples.

A transaction is a logical unit of work that consists of one or more operations or statements. It is an atomic unit, which means that either all the operations within the transaction are committed successfully, or all of them are rolled back if an error occurs. This ensures data consistency and integrity.

The following diagram illustrates how transaction management works:


       Transaction management is an essential part of enterprise applications because it ensures data integrity and consistency.

The concept of a transaction is based on the ACID properties:

  • Atomicity

  • Consistency

  • Isolation

  • Durability


  • Atomicity
           Atomicity ensures that a transaction is executed as an "all-or-nothing" operation. This means that either all the operations in a transaction are completed successfully, or none of them are.

If any operation within a transaction fails, the entire transaction is rolled back, ensuring that no partial changes are saved to the database.


  • Consistency
          Consistency ensures that the database remains in a valid and consistent state before and after a transaction. Any data written to the database must satisfy all defined constraints, rules, cascades, and triggers. If a transaction violates any of these rules, it is rolled back to maintain data integrity.

  • Isolation
             Isolation ensures that each transaction is executed independently in a concurrent environment, preventing interference from other transactions and avoiding data inconsistency or corruption.

  • Durability

Durability ensures that once a transaction has been committed, its changes are permanently saved in the database. These changes remain intact even in the event of a system crash, power failure, or other unexpected errors.

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


Programmatic transaction management: 

            Programmatic transaction management means that you explicitly write transaction management code around your business logic. Although this approach provides greater flexibility and fine-grained control over transactions, it is more difficult to maintain and results in a significant amount of boilerplate code.

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:

               Declarative transaction management separates transaction management from the business logic. Transactions are managed using annotations or XML-based configuration, making the code cleaner, easier to maintain, and less error-prone.

We will discuss declarative transaction management in detail in an upcoming post.


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-Based Configuration

        Spring configuration metadata tells the Spring container how to create, configure, wire, and assemble application objects. It provides the information required by the Spring IoC container to initialize and manage Spring beans.

Spring supports the following three types of configuration:

  • XML-based Configuration

  • Annotation-based Configuration

  • Java-based Configuration



XML Based Configuration

All configurations are defined in one or more XML files. This was the traditional way of configuring Spring applications. However, in large projects, maintaining a large amount of XML configuration can become tedious and difficult to manage.

See the example below:

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 introduced annotation-based configuration. With this approach, we still need to define some XML configuration, mainly to enable component scanning for packages containing annotated classes. However, most of the bean configuration is handled using annotations, making it easier to maintain and manage.

In this approach, we can enable annotation-based dependency injection using <context:annotation-config /> in the Spring configuration file. We can use the @Component annotation to declare a class as a Spring bean, and the @Autowired annotation to inject dependencies into the bean.

Refer to this article for more details about 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, Spring introduced a pure Java-based approach for configuring the application context. With this approach, we do not need XML configuration files. Java-based configuration provides a fully object-oriented mechanism for dependency injection, allowing developers to take advantage of features such as reusability, inheritance, and polymorphism while defining the configuration.

The application developer has complete control over bean creation and dependency injection using Java configuration.

To achieve this type of configuration, we mainly use two annotations:

  • @Configuration

  • @Bean

Java-based configuration is similar to annotation-based configuration, except that it does not rely on XML configuration files. Instead, we create Java classes and annotate them with @Configuration to define the Spring beans and their dependencies.

See the Java configuration class below:

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? Autowiring Modes and Limitations with Examples

In the previous post, we discussed the Spring IoC containers and the differences between them. In this post, we will learn about autowiring, its different modes, and its limitations in Spring.

Normally, we define bean configuration details in the Spring configuration file and explicitly specify the dependencies to be injected into other beans using the ref attribute. However, the Spring Framework also provides an autowiring feature, which eliminates the need to specify these dependencies explicitly.

Autowiring is the process of automatically injecting a bean's dependencies. Instead of configuring dependencies manually, Spring examines the beans available in the IoC container and automatically establishes the required relationships between collaborating beans.

Spring provides the following five autowiring modes:


Spring autowiring modes

  • no:

This is the default autowiring mode, which means that autowiring is disabled. Dependencies must be configured manually using the ref attribute.

Example: Using the 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:

Autowiring by Name

In this mode, Spring performs autowiring based on the property name. If the name of a bean matches the name of a property in another bean, Spring automatically injects that bean through the corresponding setter method.

Example:

In the example below, the bean named message has the same name as the message property of the chat bean. Therefore, Spring automatically injects the message bean into the chat bean by invoking the 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:

Autowiring by Type

In this mode, Spring performs autowiring based on the property data type. If the data type of a bean matches the data type of a property in another bean, Spring automatically injects the bean through the corresponding setter method.

Example:

In the example below, the data type of the message bean matches the data type of the message property in the chat bean. Therefore, Spring automatically injects the message bean into the chat bean by invoking the following 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:

Autowiring by Constructor

In this mode, Spring performs autowiring based on the constructor argument type. If the data type of a bean matches the data type of a constructor parameter, Spring automatically injects the bean through the constructor.

Example:

In the example below, the data type of the message bean matches the data type of the constructor parameter in the Chat class. Therefore, Spring automatically injects the message bean by invoking the following constructor:

public Chat(Message message)

Configuration File:

<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:--

  • Explicit configuration overrides autowiring: Dependencies specified explicitly using the constructor-arg or property elements always take precedence over autowiring.

  • Simple properties cannot be autowired: Spring cannot autowire simple properties such as primitive types, String, Class, or their wrapper classes (for example, Integer and Boolean). These values must be configured explicitly using the property or constructor-arg elements.

  • Can make configuration harder to understand: In applications with many dependencies, autowiring can make it more difficult to determine how beans are connected. Since the dependencies are resolved automatically by the container, understanding and debugging the application configuration may become more challenging.


Related Posts:--

Thursday, 4 January 2018

What Is an IoC Container? Understanding BeanFactory and ApplicationContext in Spring

         The Spring IoC (Inversion of Control) Container is the core of the Spring Framework. It is responsible for creating objects, wiring their dependencies together, configuring them, and managing their complete lifecycle—from creation to destruction.

The Spring container uses Dependency Injection (DI) to manage the components that make up an application.

The objects created and managed by the Spring container are known as Spring beans.

A Spring bean is simply an object that is created, configured, and managed by the Spring IoC container. It is not a special type of object. Any Java POJO (Plain Old Java Object) can become a Spring bean if it is configured to be initialized by the Spring container using the appropriate configuration metadata.

The Spring container determines which objects to instantiate, configure, and assemble by reading the configuration metadata provided by the application. This metadata can be specified using XML configuration, Java annotations, or Java-based configuration.

The following diagram provides a high-level overview of how the Spring IoC container works.


IOC Container in Spring


There are two types of Spring IOC Containers,
  •  BeanFactory Container
  •  ApplicationContext Container

BeanFactory Container:

             The BeanFactory is the root interface of the Spring IoC container. It is defined in the org.springframework.beans.factory package and provides the basic functionality for managing Spring beans.

BeanFactory is responsible for instantiating, configuring, and assembling application objects, as well as managing their dependencies. It uses the configuration metadata provided by the application to create and initialize Spring beans.

One of the commonly used implementations of BeanFactory was XmlBeanFactory, which allowed beans and their dependencies to be defined in an XML configuration file. XmlBeanFactory reads the XML configuration metadata and creates fully configured Spring beans.

Note: XmlBeanFactory has been deprecated since Spring 3.1 and removed in later versions of Spring. It is recommended to use ApplicationContext instead.

The following example demonstrates a 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, XmlBeanFactory loads the XML configuration file from the classpath. It reads the configuration metadata to create, configure, and manage the Spring beans. When a bean is requested, the container returns the fully initialized bean.

Finally, the getMessage() method is invoked on the bean to display the desired output.

BeanFactory is lightweight and was traditionally preferred in environments with limited resources, such as mobile devices or applets. However, in modern Spring applications, ApplicationContext is the preferred choice because it provides additional enterprise-level features.

BeanFactory is the parent interface of ApplicationContext and offers only the basic IoC container functionality. ApplicationContext extends BeanFactory and provides additional features such as event propagation, internationalization (i18n), automatic BeanPostProcessor and BeanFactoryPostProcessor registration, annotation-based configuration, and easier integration with Spring AOP.


ApplicationContext Container:--

        The ApplicationContext is defined by the org.springframework.context.ApplicationContext interface. Like BeanFactory, it can load bean definitions, create and configure beans, wire their dependencies, and provide fully initialized beans when requested.

In addition to the basic features provided by BeanFactory, ApplicationContext offers several enterprise-level capabilities, such as support for internationalization (i18n), event publishing, annotation-based configuration, automatic registration of BeanPostProcessor and BeanFactoryPostProcessor, integration with Spring AOP, declarative transaction management, and loading resources from various sources.

The following are some of the most commonly used implementations of ApplicationContext:


  • 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 org.springframework.context.ApplicationContext interfaces act as Spring IoC containers. The ApplicationContext interface extends the BeanFactory interface and provides all of its functionality along with several additional features.

ApplicationContext offers enterprise-level capabilities such as seamless integration with Spring AOP, message resource handling for internationalization (i18n), event publishing, annotation-based configuration, and application-specific contexts (such as WebApplicationContext) for web applications.

For these reasons, ApplicationContext is recommended over BeanFactory for almost all Spring applications.