Spring Data

2015-02-26 19:57:53

Spring Data is great. It simplify work with database. All you have to do, to save, update, delete or fetch entity, is create Interface.

We start from creating Entity object.

package pl.btbw.entity;

import javax.persistence.*;

@Table(name = "post")
public class Post {

    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "name")
    private String name;

    public Post() {

    public Post(int id) {
        this.id = id;

    public Integer getId() {
        return id;

    public void setId(Integer id) {
        this.id = id;

    public String getName() {
        return name;

    public void setName(String name) {
        this.name = name;

Now we create Interface

package pl.btbw.repositories;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.btbw.entity.Post;

public interface PostRepo extends JpaRepository

<post, integer=""> {

As you see it extends JpaRepository, and generally it is all.

How to use it ?

private PostRepo postRepo;


Post entity = new Post();

here you can add postRepo.flush(); or instead postRepo.save() you can use postRepo.saveAndFlush()

Fetch data

simple find all
List<post> all = postRepo.findAll();
find all with sorting
List<post> all = postRepo.findAll(
    new Sort(Sort.Direction.DESC, "id")
find all with pagination
List<post> all = map(postRepo.findAll(
    new PageRequest(1, 2)
find all with sorting and pagination
List<post> all = map(postRepo.findAll(
    new PageRequest(1, 2, new Sort(Sort.Direction.DESC, "id"))
find entities by ids
List<integer> list = new ArrayList<integer>();
List<post> all = postRepo.findAll(list);


long count = postRepo.count();

Check if item exist

boolean exists = postRepo.exists(id);

Delete item

detele item by id
delete object
delete all objects from db
delete batch of objects
List<post> list = new ArrayList<post>();
list.add(new Post(34));
list.add(new Post(35));
list.add(new Post(36));

the magic is that, that you don't neet implement PostRepo if you want to use simple crud operations. Of course if you want to add some more sophisticated queries you have to add some methods definition to this class, but this process I will describe in next post