Blog Java Introduction to Spring Data
Introduction to Spring Data

Introduction to Spring Data

The evolution of databases in recent years has been quite radical. At the time of the creation of the Spring framework, there was a relational database such as Oracle, MySQL, or MS SQL server. However, in recent times, many database variants have gained popularity even if many of them are not relational. Some of them don’t even use SQL. You can find some new names for these types of databases such as NoSQL. Now, there is nothing wrong with NoSQL databases.

However, the problem lies in the standard approach to persistence stores which depends on Data Access Objects. The use of Data Access Objects (DAO) results in the isolation of the remaining system from particular details of persistence mechanisms. The use of DAO code is monotonous and contains large volumes of similar code.

Spring Framework Basics

Also, you can face a lot of damage even due to a small error. Therefore, Spring Data came into existence for resolving these issues related to data store solutions. The following discussion is an important piece of guidance and introduction to spring data. Let us dive in to learn more about this Spring framework-based product!

Basic Insights to Know about Spring Data

The first aspect under focus in a discussion about spring data should focus on challenges in existing data store solutions. The duplication of code is one of the foremost issues related to Java Persistence API (JPA). Structural similarities in code could give the path to the similarity among additional methods written for similar codes. In such cases, the solution would be a common interface for extracting functionality from a code.

The next course of action would be the implementation of the common interface in an application. Another issue that is noted with data stores is the drastic rise in several data stores. As discussed above, many new varieties of data stores other than relational databases are becoming popular. Some of the examples of such data stores are NoSQL data stores, including Hadoop, Cassandra, and MongoDB.

ORM Frameworks such as Hibernate and specifications such as JPA were ideal for relational databases. However, the newer databases require different needs. So, persistence mechanisms solve a lot of problems in theory but also create many other problems in practice. One of the problems could be the requirement of custom annotations or configuration files.

Books are a good source to learn any technology. Check out the list of Spring Framework Books and start learning!

Functionalities of Spring Data Framework

Therefore, Spring Data gives the Abstractions or interfaces you could use without any concern for the underlying data source. The purpose of this tool is the unification and simplification of access to various types of persistence stores. You can find repositories in every type of persistence store in the form of DAOs or Data Access Objects.

These repositories generally offer CRUD operations on single domain objects as well as finder methods, pagination and sorting. You should note that CRUD refers to Create-Read-Update-Delete operations. Spring Data delivers generic interfaces for these aspects in persistence stores in the form of CrudRepository and PagingAndSortingRepository. Also, you can find facilities of implementations specific to a persistence store.

Template objects can provide ease of writing custom repository implementations. However, Spring Data’s repositories help in writing an interface with finder methods that get definitions according to specific conventions. The conventions can change according to the persistence store in use. Then, you can be assured of Spring data’s facility of the right implementation of the interface at runtime.

Commons and CRUD Repository

Now that we have insights from introduction to spring data let us move towards the interfaces. The first interface is Spring Data Commons which is a source for all common abstractions. You can use the common abstractions for connecting with various data stores. Users could find the Crud Repository in Commons as a reliable place for generic CRUD operations. The underlying data store does not have any impact on the facility of operations. Crud Repository extends the ‘Repository’ base class, which is ideal for all repositories that provide access to data stores. The different methods in Crud Repository are presented as follows.

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

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

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

Optional<T> findById(ID id);

boolean existsById(ID id);

Iterable<T> findAll();

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

long count();

void deleteById(ID id);

void delete(T entity);

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

void deleteAll();

}

You should also note that the methods in Crud Repository provide explanations on their own.

Paging and Sorting Repository

The next significant interface in Spring Data is the PagingAndSortingRepository. Users can find this repository helpful for sorting data by using the “Sort” interface. The repository also helps in the pagination of data by using “Pageable” interface. The “Pageable” interface provides different methods for pagination such as getPageSize( ), getPageNumber( ), previousOrFirst( ), getPageSize( ) and others. An example of using the PagingAndSortingRepository can be shown as follows.

public abstract interface PagingAndSortingRepository extends CrudRepository {

public Iterable findAll(Sort sort);

public Page findAll(Pageable pageable);

}

Definition of custom repositories

Another crucial aspect of this discussion shall reflect on the definition of custom repositories in Spring Data. Users can create custom repositories by extending one of the repository classes such as Repository, CrudRepository, and PagingAndSortingRepository. Here is an example of defining custom repositories.

interface PersonRepository extends CrudRepository<User, Long> {

Definition of custom queries

You can also find the facility of defining custom queries through interface method names. Here is an example of defining custom queries.

List<Person> findByFirstNameAndLastname(String firstName, String Lastname);

The method mentioned above can help in searching a data store with the first name and last name of a person. As a result, you can create a relevant query for the data store to obtain the details of the person.

Auditing Features

Users could also find features for auditing with Spring Data in the form of simple annotations. Take a look at the example below.

class Student {

@CreatedBy

private User createdUser;

@CreatedDate

private DateTime createdDate;

// … further properties omitted

}

You could also find relevant annotations for updates such as “LastModifiedBy” and “LastModifiedDate.”

Exploring the Spring Data JPA Implementation

After a thorough introduction and discussion on various types of interfaces, let us proceed towards Spring Data JPA. You can find different modules or implementations that are ideal for specific data stores. The JPA implementation is suitable for connection to relational databases using ORM frameworks. A closer look at its definition and various features along with explanation can refine this discussion further.

Built on the very popular and effective Spring framework, Spring Data JPA is one of the core projects in the suite of tools of Spring. The implementation develops the functionality of JPA or Java Persistence API. Expansion of feature set and application complexity can result in the growth of persistence tier code and Data Access Layer. The JPA implementation helps in building responsive and smart Spring Repository stereotyped interfaces.

As a result, you could be able to reduce code and simplify the Data Access Layer. The best thing here is that you do not have to compromise on the functionalities of the application. Developers can define a data access contract with the help of these repositories. Then, the JPA implementation could evaluate the data access contract and automatically develop the interface implementation.

Preparing for Spring Framework interview? Go through these frequently asked Spring framework interview questions and get ready to ace the interview.

However, a Query DSL is important for developing an implementation of the Repository interface. The DSL or Domain Specific Language helps in the creation of Java interface methods. The interface methods use specific keywords in unison with certain JPA entity attributes for correct implementation of queries.

The Spring Data JPA example illustrations can also help you find insights into many other features. Many of the features are visible and applied in Data Access Layers in persistence tiers. You can also find features of auditing, paging, and managing native SQL queries with the JPA implementation. Furthermore, the JPA framework also provides flexibility in the event of its inability to address the Data Access Layer requirements.

The JPA framework would move out of the way and allow you for coding or working parallel to the framework. You could also work outside the framework completely without any obstacles. The ease of connection to relational databases using ORM frameworks improves considerably with JPA implementation. The Spring Data JPA example of dependency can be seen as follows.

<dependencies>

<dependency>

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

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

</dependency>

</dependencies>

By default, the JPA implementation is Hibernate, and the core interface is the JpaRepository. Take a look at the following syntax.

public interface JpaRepository<T, ID>

 extends PagingAndSortingRepository<T, ID>, 

         QueryByExampleExecutor<T>

You can also find additional methods in the JPA implementation when compared with PagingAndSortingRepository. You should also note that all the additional methods are specifically related to JPA.

/**

 * Saves an entity and flushes changes instantly.

 *

* @param entity

 * @return the saved entity

 */

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

 /**

 * Deletes the given entities in a batch which means it will create a single {@link Query}. Assume that we will clear

 * the {@link javax.persistence.EntityManager} after the call.

 *

 * @param entities

 */

void deleteInBatch(Iterable<T> entities);

/**

 * Deletes all entities in a batch call.

 */

void deleteAllInBatch();

Conclusion

The discussion mentioned above helped in obtaining a brief introductory explanation on Spring Data. The extensiveness of development requirements alongside the changes in databases over the years demands top Java frameworks. Therefore, the amazing Spring framework resource helps in obtaining abstractions to store and retrieve data from a data store.

The JPA implementation is an extension of the Spring’s Data framework. The JPA implementation is ideal for connecting to JPA and involves communication with relational databases. The most important benefit of Spring’s Data framework is the flexibility to switch between data stores.

If you want to master Spring’s Data framework, this might be the right point. As a beginner, you can also enroll in our Spring Framework Basics Online Course and start your journey to become a Spring professional!

About Neeru Jain

Technology Scientist by Mind and Passionate Writer by Heart!! With an enthusiasm for technological research and learning, Neeru turned out to be a technology expert. Her Belief: “Words are powerful enough to change Mind, Life, and the World; only the writer should have a real passion for Writing!!”
Spread the love

LEAVE A REPLY

Please enter your comment!
Please enter your name here