How to integrate Spring data to Spring MVC app

0
44
views

 This tutorial will tell how java development company professionals integrate Spring Data to Spring MVC app. You can follow the steps shared by experts in this post and learn how they integrate spring data in MVC app.

Spring Data is one of the implementation of JPA2.0 (Java Persistence API), spring data is implemented using spring core and spring MVC. Spring Data will makes it easy to connect to relational databases and non-relational databases.

Spring Data provides all abstractions/sub-modules specific to Database.

EG: for Relational Databases spring Data has sub-module called Spring-Data-JPA, and for MongoDB Spring-Data-MongoDB is the sub-module.

Using Spring Data Repository Interfaces the Queries to Databases will generate dynamically based on method names we provided.

Spring Data has one important sub-module called Spring-Data-Envers which is used for Entity Versioning using Hibernate Envers.

Using Spring Data we can easily plugin various functionalities like Elastic Search, Envers.

Using Spring Profile Concept we can connect to various Databases based on active profile.

EG: suppose our custom interface implements JPARepository and RevisionRepository, custom repository will implements the JPA related operations and also it supports entity versioning without writing any code.

We can configure Spring Data,Spring-Data-JPA will only work if the active profile is JPA, if the active profile is Mongo then it will connect to MongoDB.
Spring Data to Spring MVC app

Integrating Spring Data to Spring MVC application:

Changes required in pom.xml file:

<dependencyManagement>

<dependencies>
<dependency>

<groupId>org.springframework.data</groupId>

<artifactId>spring-data-releasetrain</artifactId>

<version>Hopper-SR2</version>

<scope>import</scope>

<type>pom</type>

</dependency>

</dependencies>

</dependencyManagement>

 

And we need to spring data related dependency:

<dependency>

<groupId>org.springframework.data</groupId>

<artifactId>spring-data-jpa</artifactId>

</dependency>

 

Integrating Spring Data with Spring Boot application:

Changes required in pom.xml file:

<dependency>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

 

Spring Data will provide Repository marker interface, for CRUD (create,read,update,delete) related operations spring data provides CrudRepository which extends Respository interface.

Spring data CrudReposiroty will provides the following methods:

public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {

      <S extends T> S save(S entity);

      <S extends T>Iterable<S>save(Iterable<S> entities);

      T findOne(ID id);

      boolean exists(ID id);

      Iterable<T>findAll();

      Iterable<T>findAll(Iterable<ID> ids);

      long count();

      void delete(ID id);

      void delete(T entity);

      void delete(Iterable<? extends T> entities);

      voiddeleteAll();

}

 

Where T means entity type,ID type of primary key object (like Integer,Long etc…)

And all methods present in CrudRepository are self-explanatory.

EG: Save method is used to save the entity (table name and column details will be extracted from entity definition), it will return the whole object with generated values if any are there.

For supporting Paging and Sorting capabilities Spring data provides new interface extending CrudRepository is called PagingAndSortingRepository.

The additional methods provided by this interface will be:

Iterable<T>findAll(Sort sort);

This method is used to get the collection of object using specified order.

Page<T>findAll(Pageablepageable);

This method is used to retrieve the documents using pagination, like having pageNumber and pagesize.

Spring Data JPA provides extension to PagingAndSortingRepository interface called JpaRepository which will support all CRUD related methods.

The JPARepository Interface will look like below:

public interface JpaRepository<T,ID extends Serializable> extends PagingAndSortingRepository<T, ID> {

      List<T>findAll();

      List<T>findAll(Sort sort);

      List<T>findAll(Iterable<ID> ids);

      <S extends T> List<S>save(Iterable<S> entities);

      void flush();

      <S extends T> S saveAndFlush(S entity);

      voiddeleteInBatch(Iterable<T> entities);

      voiddeleteAllInBatch();

      T getOne(ID id);

}

 

For MongoDB spring-data-mongoDB extension plugin provides MongoRepository extending PagingAndSortingRepository to support all mongoDB related operation.

 

Creating Custom Repository for JPA:

Spring Data will provides 2-ways to create Repositories.

1) We can write an interface extending JpaRepository and we need to annonate with Repository (provided by Spring MVC), we can write own methods.

2) We can create class and annonate with @RepositoryDefinition, so that spring data automatically will detect annotation and it will create Repository bean.

 

The method name either should follow spring Data rules or we can annonate with @Query annotation.

  1. If we follow Spring Data method name convention Spring Data will generate SQL query.

EG: public Person findByNameAndAge (String name,int age); this method name inform the Spring data fetch the records using name and age in where condition.

 Generated query will look like this:

Select * from persons p where p.name=<name> and a.age=<age>. name and age are the method parameters.

Select * from persons p where p.name=?1 and a.age=?2. 1 and 2 are the positional method arguments.

  1. If we annonate with Query annotation we need to specify the SQL query that we want to execute when we call method.

Eg: @Query(Select * from persons p where p.name=$name and a.age=$age)

Name and age values will be replaced by method parameters.

Eg: PersonRepository class:

packageorg.example.repository;




importorg.example.model.Person;

importorg.springframework.data.jpa.repository.JpaRepository;

importorg.springframework.stereotype.Repository;




@Repository

publicinterfacePersonRepositoryextendsJpaRepository<Person, Long>{

}

By default all methods will be executed in Read-only Transactional Mode.

If method is tries to change the state like creation, updation, deletion then the method should be annonated with Modifying.This annotation will inform spring data that the method should executed in Write Transactional Mode.

Additional Changes/configuration for bootstrapping Spring Data Annotations:

  • We need to add annotation EnableJpaRepositories in Spring Configuration files, we can specify the base-packages for scanning spring data annotations.
  • XML Configuration:Spring Data provides new schema for XML Configuration.
<?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:jpa="http://www.springframework.org/schema/data/jpa"

xsi:schemaLocation="http://www.springframework.org/schema/beans

     http://www.springframework.org/schema/beans/spring-beans.xsd

     http://www.springframework.org/schema/data/jpa

http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

<jpa:repositories base-package="org.example.controller"/>

</beans>

Spring Boot Configuration for Spring Data:

@SpringBootApplication

@EnableJpaRepositories

@EnableTransactionManagement

publicclassSpringBootDataApplication {




      publicstaticvoid main(String[] args) {

            SpringApplication.run(SpringBootDataApplication.class, args);

      }

}

If we don’t specify basePackages attribute for EnableJpaRepositories annotation, by default it will scan the current package and child packages to it.

@EnableTransactionManagement will makes sure that every database query will perform in transaction.

Sample project to demonstrate Spring Data:

Pom.xml file:

<?xmlversion="1.0"encoding="UTF-8"?>

<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

      <modelVersion>4.0.0</modelVersion>




      <groupId>org.example</groupId>

      <artifactId>Spring-Boot-Data-Example</artifactId>

      <version>0.0.1-SNAPSHOT</version>

      <packaging>jar</packaging>




      <name>Spring-Boot-Data</name>

      <description>Integrating Spring Boot and Spring Data</description>




      <parent>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-parent</artifactId>

            <version>1.3.5.RELEASE</version>

            <relativePath/><!-- lookup parent from repository -->

      </parent>




      <properties>            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

            <java.version>1.8</java.version>

      </properties>




      <dependencies>

            <dependency>

                  <groupId>org.springframework.boot</groupId>

                  <artifactId>spring-boot-starter-data-jpa</artifactId>

            </dependency>

            <dependency>

                  <groupId>org.springframework.boot</groupId>

                  <artifactId>spring-boot-starter-data-rest</artifactId>

            </dependency>

            <dependency>

                  <groupId>org.springframework.boot</groupId>

                  <artifactId>spring-boot-starter-web</artifactId>

            </dependency>




            <dependency>

                  <groupId>mysql</groupId>

                  <artifactId>mysql-connector-java</artifactId>

                  <scope>runtime</scope>

            </dependency>

            <dependency>

                  <groupId>org.springframework.boot</groupId>

                  <artifactId>spring-boot-starter-test</artifactId>

                  <scope>test</scope>

            </dependency>

      </dependencies>




      <build>

            <plugins>

                  <plugin>

                        <groupId>org.springframework.boot</groupId>

                        <artifactId>spring-boot-maven-plugin</artifactId>

                  </plugin>

                  <plugin>

                        <artifactId>maven-compiler-plugin</artifactId>

                        <configuration>

                              <source>1.8</source>

                              <target>1.8</target>

                        </configuration>

                  </plugin>

            </plugins>

      </build>

</project>

 

Spring boot Main class:

 

packageorg.example;

importorg.springframework.boot.SpringApplication;

importorg.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import org.springframework.transaction.annotation.EnableTransactionManagement;




@SpringBootApplication

@EnableJpaRepositories

@EnableTransactionManagement

publicclass SpringBootDataApplication {




   public static void main(String[] args) {

         SpringApplication.run(SpringBootDataApplication.class, args);

   }

}

Person Controller class:




@RestController

publicclassPersonController {

      @Autowired

      privatePersonRepositorypersonRepository;

      @RequestMapping(value="/persons",produces=MediaType.APPLICATION_JSON_VALUE)

      public List<Person>getAllPerson(){

            returnpersonRepository.findAll();

      }

}

PersonRepository class:




@Repository

publicinterfacePersonRepositoryextendsJpaRepository<Person, Long>{

}

Entity Classes:

@Entity

@Table(name="persons")

publicclass Person {

      @Id

      @GeneratedValue(strategy=GenerationType.IDENTITY)

      privatelongid;

      @Column(name="first_name")

      private String firstName;

      @Column(name="last_name")

      private String lastName;

      @Column(name="mobile_number")

      private String mobileNumber;

      @Column(name="email")

      private String email;

      @OneToMany

      @JoinColumn(name="PERSON_ID")

   private List<Address>addresses = newArrayList<>();

// setters and getters

}




@Entity

@Table(name="Address")

publicclass Address {

      @Id

      @GeneratedValue(strategy=GenerationType.IDENTITY)

      privatelongid;

      @Column(name="address_1")

      private String addressLine1;

      @Column(name="address_2")

      private String addressLine2;

      @Column(name="address_3")

      private String addressLine3;

      @Column(name="city")

      private String city;

      @Column(name="state")

      private String state;

      @Column(name="country")

private String country;

// setters and getters

}

If you the spring boot application the sample output will be look like:

 

[

  {

    "id": 1,

    "firstName": "sravan",

    "lastName": "kumar",

    "mobileNumber": "9876543210",

    "email": "sravan@gmail.com",

    "addresses": [

      {

        "id": 1,

        "addressLine1": "add1",

        "addressLine2": "add2",

        "addressLine3": "add3",

        "city": "hyd",

        "state": "telangana",

        "country": "india"

      },

      {

        "id": 2,

        "addressLine1": "add4",

        "addressLine2": "add5",

        "addressLine3": "add6",

        "city": "ahmed",

        "state": "gujarat",

        "country": "india"

      }

    ]

  },

  {

    "id": 2,

    "firstName": "kumar",

    "lastName": "sravan",

    "mobileNumber": "1234567890",

    "email": "kumar@gmail.com",

    "addresses": []

  }

]

 

You can download the sample application

https://github.com/sravan4rmhyd/Spring-Boot-Data.git

 

The purpose of intending this article is to make you clear how java development company experts are integrating Spring Data to spring MVC application. Still in case there are doubts, you can write to them and ask freely.

Author Bio:

Prashant is a Java professional working in reputed Java Development Company. She has authored many articles on java and java application development. You can write to the author for more info about the Spring Data or MVC app.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here