What is Spring Data?

(This is related to Project Student and I will revisit this topic later.)

Spring Data came up in passing in several recent interviews. What is Spring Data?

To answer that let’s consider the standard approach to persistence – all access is made via Data Access Objects (DAOs). This completely isolates the rest of the system from the specific details of the persistence mechanisms. This sounds easy but anyone who has ever done a non-trivial project knows there’s a big headache.

DAO code is boring.

It’s monotonous, it has a lot of very similar code, and a slight error can cause a lot of damage. Worse it violates the Don’t Repeat Yourself (DRY) principle since most of the information is already captured in JPA annotations.

This is such a big problem that there have been code generation tools for years. In theory they solve the problems but in practice they introduce their own. E.g., the need for custom configuration files or annotations.

Using an interface as a DRY contract

What is the ultimate DRY contract in the Java world? That’s easy – it’s an Interface. Given an interface and a template we can use CGLib to generate the necessary classes on the fly during application startup. There’s a slight performance hit but it’s modest when compared to the benefits.

Student.java

@Entity
public class Student {
    private Integer id;
    private String uuid;
    private String name;
    private String emailAddress;
    private Integer creditHours;

    @Id
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }

    @Column(unique=true)
    public String getUuid() { return uuid; }
    public void setUuid(String uuid) { this.uuid = uuid; }

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

    @Column(unique=true)
    public String getEmailAddress() { return emailAddress; }
    public void setEmailAddress(String emailAddress) { this.emailAddress; }

    @Column
    public Integer getCreditHours() { return creditHours; }
    public void setCreditHours(Integer creditHours) { this.creditHours = creditHours; }
}

What could our Interface look like?

repository/StudentRepository.java

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends CrudRepository<Student, Integer> {
    // this could also be getByUuid() or fetchByUuid() - all are recognized
    Student findStudentByUuid(String uuid);

    Student findStudentByEmailAddress(String emailAddress);

    List<Student> findStudentsByNameLike(String pattern);

    // we can use a custom query
    @Query("select s from Student s where s.creditHours < 15")
    List<Student> findFreshmen();
}

and so on. In all there are 15 predicates that can be used alone or in combination.

  • And
  • Or
  • Between
  • LessThan
  • GreaterThan
  • IsNull
  • IsNotNull
  • NotNull
  • Like
  • NotLike
  • OrderBy
  • Not
  • In
  • NotIn
  • IgnoreCase

N.B., it is not necessary to implement this interface! CGLib takes care of that for us.

Custom Methods

Sometimes we need to write our own DAO methods. They are easy to integrate into the generated code.

public interface StudentExtras {
   Student flogStudent(Student student);
}

@Repository
public interface StudentRepository extends CrudRepository<Student, Integer>, <em>StudentExtras</em> { }

// this class does NOT implement StudentRepository!
public class StudentRepositoryImpl implements StudentExtras {
    public Student flogStudent(Student student) { ... }
}

The custom methods must be a specific class (due to configuration by convention) but are otherwise unrestricted.

NoSQL

Spring Data also transparently supports NoSQL databases: Mondo (documents), Neo4j (graph), Redis (key-value), Hadoop (map-reduce) and GemFire.

Pagination

Finally we have the question of pagination. User interfaces typically only look at a subset of the available information, e.g., a page of 25 items. Pagination isn’t difficult, just boring and error-prone.

Spring Data supports pagination by extending the PagingAndSortingRepository interface instead of the CrudRepository interface.
 

Reference: What is Spring Data? from our JCG partner Bear Giles at the Invariant Properties blog.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

2 Responses to "What is Spring Data?"

  1. Maxim S. Ivanov says:

    Do you mean Mongo DB? I don’t know NoSQL databases name as Mondo :)

  2. Valery Silaev says:

    In 2008 I were using “warp persist” with Google Guice – almost identical library ( in terms of functionality)
    So it seems that support for Mongo is the only innovation added by Spring team.

Leave a Reply


− one = 2



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close