Spring XML Based DI and Builder Pattern

Spring XML Based DI and Builder Pattern



Recently, I had faced a situation where a project using Spring framework for its Business layer and maintains the Spring dependencies in the XML file. They can not upgrade this XML based configuration to java based configuration as this project is old it will take time and they can’t afford it.

That is fine but the problem is they want to add a third party module (another module developed by other set of developers of that project family) to re-use some utilities of that library.

But when they try to incorporate aforesaid module they discovered that many classes which are exposed as services were created using Builder pattern. So we will see here How we can incorporate Builder pattern in Spring XML-based DI.

Builder Pattern :

In a brief Builder pattern is used to create complex Object,  which has some required and some optional parameters,

We create a static inner class called Builder and pass require parameters in the constructor of that builder. Then set Optional parameter calling the Setter method of that Builder.

Lastly, it has a build() method, which will produce the actual Object.

Say, We create an Employee Object using builder pattern where id and the name of the employee are mandatory but a hobby, gender, address are optional.


Code:

package com.example.advanceSpring.entity;

public class Employee {
   
    private Long id;
    private String name;
    private int gender;
    private String address;
    private String hobby;
    private Employee()
    {
       
    }
   
    public static class EmployeeBuilder{
       
        private Long id;
        private String name;
        private int gender;
        private String address;
        private String hobby;
       
        public EmployeeBuilder(Long id, String name)
        {
            this.id=id;
            this.name=name;
        }
       
        public void setGender(int gender)
        {
            this.gender = gender;
       
        }
        public void setAddress(String address)
        {
            this.address = address;
           
        }
        public void setHobby(String  hobby)
        {
            this.hobby = hobby;
           
        }
       
        public Employee build()
        {
            Employee emp = new Employee();
            emp.id=id;
            emp.name=name;
            emp.gender=gender;
            emp.address=address;
            emp.hobby=hobby;
            return emp;
                   
        }
    }

    @Override
    public String toString() {       
        return "Employee [id=" + id + ", name=" + name + ", gender="+( gender == 1?"Male":"Female") + ", address=" + address + ", hobby="
                + hobby + "]";
    }
   
   
   

}



Say, This class comes from a third party jar and we need to create Employee Object using Spring Xml based Dependency injection.

How we can achieve this?

Step 1. Register the builder class using the context of Employee class with $. So class attribute will be look like this

Class =”com.example.advanceSpring.entity.Employee$EmployeeBuilder” by doing this Spring will understand Employee builder is an inner class of Employee.

Step 2: pass the required parameters using constructor-args.
Step3: Pass the optional parameter using property tag.
Step 4: Register the Employee bean in Spring XML, While registering one thing you can notice that Employee Object constructor is private so Spring bean can’t call it by reflection. So we will use the factory-bean and  the factory-method attribute of spring xml.

factory-bean tells Spring to use the bean as a Factory class for creating the Object, so here Spring treats EmployeeBuider as a Factory of Employee Object.

factory-method tells Spring to, upon calling the method instance of the Object will return so here build() method act as factory method to create Employee Object.

The Spring  Xml file

<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-2.5.xsd">

    <bean id="helloBean" class="com.example.advanceSpring.HelloWorld">
        <property name="name" value="Shamik" />
    </bean>
   
    <bean id="builder" class="com.example.advanceSpring.entity.Employee$EmployeeBuilder">
        <constructor-arg value="1"/>
       <constructor-arg value="Shamik Mitra"/>
       <property name="gender" value="1"/>
       <property name="hobby" value="Blogging"/>
    </bean>
    <bean id="employee" class="com.example.advanceSpring.entity.Employee" factory-bean="builder" factory-method="build"/>
   

</beans>


Step5: Now we will test the settings.



import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.example.advanceSpring.entity.Employee;


public class SpringTest {
   
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "SpringTest.xml");

        Employee employee = (Employee) context.getBean("employee");
        System.out.println(employee);
    }

}


Step 6:  Output:

Employee [id=1, name=Shamik Mitra, gender=Male, address=null, hobby=Blogging]



Please note that If the Setter method using Fluent Style, that is calling setter it return the instance of that object(this) then Spring can’t call this Setter as this is not the method signature Spring calls internally.

Spring Data (Part 5): Paging and Sorting

Paging and Sorting


Overview

When we perform bulk operations, like finding all "Person"s from the database or finding everyone based on a country, often we do the paging so that we can present a small data chunk to the end user and, in the next request, we fetch the next data chunk. By doing this, we got two main advantages.

Advantages

Enhancing readability for end users if we show whole data on a page then the page will be enough long with Scrollbar, the end user has to scroll for finding a particular person which is a bad UI design.
Reduce the Query time and enhance the performance as in spite of fetch all data we only fetch a small chunk of data so less query time. Many UI technology support client side paging which at a time fetch all data and based on use request show paginated data but this is not reducing the query time it only provide the advantage number 1.

Disadvantages:
To request every data chunk One server trip is required. You can optimize it through caching .
2 . When an end user in the process of fetching data another Person added to the system it may possible, the last entry of a page again shown in next page as a first entry.

But we are always using paging to fetch a small chunk of data rather than whole data.

Spring Data and Pagination

Spring data provides support for pagination , It creates all the logic to implement a paging like a count the rows for total pages , create data store specific queries etc.
To implement Paging is very easy in Spring data just we need to follow the below steps,
1. In your custom repository just extends PagingAndSortingRepository
2. Create a PageRequest Object which is an implementation of Pageable interface
This PageRequest Object takes page number, limit of the page (page size) and sorts direction and sort field.
3. By passing requested page number and page limit you can get the data for this page.
If you pass a wrong page number Spring data will take care of that and not return any data.

Paging Code implementation
1. Create a repository which extends PagingAndSortingRepository

package com.example.repo;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import com.example.person.Person;
@Repository
public interface PersonRepositary extends PagingAndSortingRepository<Person, Long>,QueryDslPredicateExecutor<Person> {
@Query("select p from Person p where p.country like ?1 order by country")
List<Person> findByCountryContains(String country);
List<Person> findPersonByHobbyName(String name);
@Query("select p from Person p where p.id = ?1 and  country='America'")
Person findOne(Long id);
}
 
 
2.Create Domain Objects
 
package com.example.person;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Person {
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
private String country;
private String gender;
@OneToMany(mappedBy="person",targetEntity=Hobby.class,
       fetch=FetchType.EAGER,cascade=CascadeType.ALL)
List<Hobby> hobby;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<Hobby> getHobby() {
return hobby;
}
public void setHobby(List<Hobby> hobby) {
this.hobby = hobby;
}
public void addHobby(Hobby ihobby)
{
if(hobby == null)
{
hobby = new ArrayList<Hobby>();
}
hobby.add(ihobby);
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", country=" + country + ", gender=" + gender + "]";
}
}



3. Fetch all person, Here I assume per page entry is one so create a PageRequest Object with limit 1 and requesting for the first page.

package com.example.person;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.example.repo.HobbyRepository;
import com.example.repo.PersonRepositary;
import com.querydsl.core.types.dsl.BooleanExpression;
@SpringBootApplication
@EnableJpaRepositories("com.example.repo")
public class PersonApplication {
@Autowired
HobbyRepository hRepo;
private static final Logger log = LoggerFactory.getLogger(PersonApplication.class);
@Bean
public CommandLineRunner demo(PersonRepositary repository) {
findAll(repository);
return null;
}
private PageRequest gotoPage(int page)
{
PageRequest request = new PageRequest(page,1)
return request;
}
private void findAll(PersonRepositary repository)
{
Iterable<Person> pList = repository.findAll(gotoPage(0));
for(Person p : pList)
log.info("Person " + p);
}
public static void main(String[] args) {
 SpringApplication.run(PersonApplication.class, args);
}
}
 
 

Output
 
 
Hibernate: 
    select
        count(person0_.id) as col_0_0_ 
    from
        person person0_
Hibernate: 
    select
        person0_.id as id1_1_,
        person0_.country as country2_1_,
        person0_.gender as gender3_1_,
        person0_.name as name4_1_ 
    from
        person person0_ limit ?
Person Person [id=13, name=Samir mitra, country=America, gender=male]
 


Paging and Sorting Code implementation:

To do sorting we have to pass the sort direction and sorting fields along with page number and limit. Suppose we want to sort by country name in ascending order we modify the goto
 method like following.

private PageRequest gotoPage(int page)
{
PageRequest request = new PageRequest(page,1,Sort.Direction.ASC,"country");
return request;
}
 
 
 
Output:
 
 select
        count(person0_.id) as col_0_0_ 
    from
        person person0_
Hibernate: 
    select
        person0_.id as id1_1_,
        person0_.country as country2_1_,
        person0_.gender as gender3_1_,
        person0_.name as name4_1_ 
    from
        person person0_ 
    order by
person0_.country asc limit ?



Here we pass the ascending order and country property.