/java/

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.*;

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

    @Id
    @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;

@Repository
public interface PostRepo extends JpaRepository

<post, integer=""> {
}

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

How to use it ?

@Autowired
private PostRepo postRepo;

Create

Post entity = new Post();
entity.setName(name);
postRepo.save(entity);

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.add(1);
list.add(2);
List<post> all = postRepo.findAll(list);

Count

long count = postRepo.count();

Check if item exist

boolean exists = postRepo.exists(id);

Delete item

detele item by id
postRepo.delete(id);
delete object
postRepo.delete(post);
delete all objects from db
postRepo.deleteAll();
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));
postRepo.deleteInBatch(list);

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