Spring Data JPA Tutorial:crud

Source: Internet
Author: User
Tags findone java se

http://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-two-crud/

We have now configured the persistence layer of our Spring application. We are the finally ready-to-create our first Spring Data JPA repository.

This blog post describes how we can create a repository that provides CRUD operations for TODO entries.

Let ' s get started.

Additional Reading:

If you aren't familiar with Spring Data JPA, you should read The following blog posts before you continue Readin G This blog post:

    • Spring Data JPA Tutorial:introduction provides a quick Introduction to Spring data JPA and gives an overview of the Sprin G Data repository interfaces.
    • Spring Data JPA tutorial:getting The Required Dependencies describes how can get the Required Dependencies.
    • Spring Data JPA tutorial:configuration Describes how can configure the persistence layer of a Spring application that Uses Spring Data JPA.
Creating the Repository

Before we can create our first Spring Data JPA repository and we have to create a entity class that contains the information of a single TODO entry. The relevant part of the Todo class looks as follows:

123456789101112131415161718192021222324252627282930313233343536373839 import org.hibernate.annotations.Type; import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.PrePersist;import javax.persistence.Table;import javax.persistence.Version;import java.time.ZonedDateTime;@Entity@Table(name = "todos")final class Todo {    @Id    @GeneratedValue(strategy = GenerationType.AUTO)    private Long id;    @Column(name = "creation_time", nullable = false)    @Type(type = "org.jadira.usertype.dateandtime.threeten.PersistentZonedDateTime")    private ZonedDateTime creationTime;    @Column(name = "description", length = 500)    private String description;    @Column(name = "modification_time")    @Type(type = "org.jadira.usertype.dateandtime.threeten.PersistentZonedDateTime")    private ZonedDateTime modificationTime;    @Column(name = "title", nullable = false, length = 100)    private String title;    @Version    private long version;        //The constructor, builder, and other methods are omitted}
Additional Reading:

    • Hibernate Reference documentation:6.4 Custom Types
    • The Javadoc of the Persistentzoneddatetime class

We are now ready to create our first Spring Data JPA repository. We can create the repository that provides CRUD operations for Todo objects by using one of the following methods :

    1. Create an interface that extends the crudrepository interface.
    2. Create an interface This extends the Repository interface and add the required methods to the created interface.

Let's take a closer look at these methods.

Extending the crudrepositoryInterface

If we create our repository by extending the crudrepository interface, we had to provide the type parameters:

    1. The type of the entity is managed by our repository.
    2. The type of the entity ' s ID field.

In other words, when we create the repository, this provides CRUD operations for Todo objects, we had to provide The following type parameters:

    1. The type of the entity is Todo.
    2. The type of the entity ' s ID field is Long.

The source code of the todorepository interface looks as follows:

12345 importorg.springframework.data.repository.CrudRepository; interface TodoRepository extends CrudRepository<Todo, Long> {}
Additional Reading:

    • The Javadoc of the crudrepository interface
    • Spring Data JPA Reference manual:2.3 defining Repository Interfaces

The crudrepository interface declares many methods, but the methods that is relevant for this blog post is de Scribed in the following:

    • The void Delete (T entity) method deletes the entity whose ID is given as a method parameter.
    • The iterable<t> findAll () method returns all entities that is saved to the database.
    • The T findOne (Long ID) method returns the entity whose ID is given as method parameter. IF No entity is found, the This method returns null.
    • The T-save (T entity) method saves the entity given as a method parameter and returns the persisted entity.
The service class that provides CRUD operations for TODO entries uses these methods for fulfilling its responsibilities.

Let's find out what we can create a repository interface that extends the repository interface.

Extending the RepositoryInterface

If we create our repository by extending the repository interface, we had to follow these steps:

    1. Provide the type parameters:
      1. The type of the managed entity (Todo).
      2. The type of the entity ' s ID field (Long).
    2. Add the required methods to the Repository interface:
      1. The void Delete (Todo deleted) method deletes the Todo object given as a method parameter.
      2. The list<todo> findAll () method returns all Todo objects that is found from the database.
      3. The optional<todo> findOne (Long ID) method finds the Todo entry whose ID is given as a method parameter. If No Todo entry is found, this method returns an empty Optional.
      4. The todo save (Todo persisted) method saves the Todo object given as a method parameter and returns t He persisted object.

The source code of the todorepository interface looks as follows:

123456789101112131415 import org.springframework.data.repository.Repository;import java.util.List;import java.util.Optional;interface TodoRepository extends Repository<Todo, Long> {    void delete(Todo deleted);     List<Todo> findAll();    Optional<Todo> findOne(Long id);    Todo save(Todo persisted);}
If we don ' t want to return Optional(Guava/java 8) objects, we can also use the "traditional" Todo FindOne (Long ID)Method.

Additional Reading:

    • The Javadoc of the Repository interface
    • Spring Data JPA Reference manual:2.3.1 fine-tuning repository definition
    • What's New in Spring Data Dijkstra (search for ' support for wrapper types as return values ')

Let's move on and the Find out which method we should use.

Which Method should We use?

It depends.

I know that's probably the most annoying answer one can give to a question. That's why I created II rules that we can follow when we are creating Spring Data JPA repositories. These rules are:

    • If we want to expose all repository methods that is declared by the crudrepository interface and we don ' t want to return Optional (Guava/java 8) objects, our repository interfaces should extend the Crudreposito Ry interface.
    • If we don ' t want to expose all repository methods that is declared by the crudrepository interface OR W e want to return Optional (Guava/java 8) objects, our repository interfaces must extend the repository Interface.

Case Closed?

Not exactly. I argue that we shouldalways use the second method. This opinion was based on the reasons:

    • When we create a interface, we should not add unnecessary methods to it. We should keep the interface as small as possible because small interfaces is easier to use and they help us to create Co Mponents that has only one job.
    • Optional helps us to create better APIs because it reveals this there might not be a return value.
Additional Reading:

    • Minimal Interface
    • Intention revealing Code with Java 8 ' s New Type ' Optional '
    • Tired of Null Pointer Exceptions? Consider Using Java SE 8 ' s Optional
    • The Design of Optional
    • Java 8 Optional Objects

If we create our repositories by extending the Repository interface and adding the required methods to the Create D repository interfaces, we need to add the ' same ' methods to every interface. Right?

wrong.

We can avoid this by following these steps:

    1. Create a base interface that extends the Repository interface and add the common methods to that interface.
    2. Create the actual repository interface that extends our base interface.

Let's move on and take a closer look at these steps.

First, we have to create a base interface that declares the methods gkfx by our repositories. We can do this by following these steps:

    1. Create the baserepository interface that extends the Repository interface. This interface has both type parameters:
      1. T describes the type of the managed entity.
      2. ID describes the type of the entity ' s ID field.
    2. Annotate the created interface with the @NoRepositoryBean annotation. This ensures, Spring Data JPA doesn ' t try to create a implementation for our base repository interface.
    3. Add the common methods to the created interface.

The source code of the baserepository interface looks as follows:

1234567891011121314151617 import org.springframework.data.repository.NoRepositoryBean;import org.springframework.data.repository.Repository;import java.util.List;import java.util.Optional;@NoRepositoryBeaninterface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {    void delete(T deleted);     List<T> findAll();        Optional<T> findOne(ID id);    T save(T persisted);}
Additional Reading:

    • The Javadoc of the @NoRepositoryBean annotation

Second, we have to create the actual repository interface this extends our base interface. We can do this by following these steps:

    1. Create the todorepository interface.
    2. Extend the baserepository interface and provide the type parameters:
      1. The type of the managed entity is Todo.
      2. The type of the entity ' s ID field is Long.

The source code of the todorepository interface looks as follows:

123 interfaceTodoRepository extends BaseRepository<Todo, Long> {}

We have now created a repository hierarchy This allows us to:

    • Create repositories that provides CRUD operations for entities without declaring the ' same ' methods in every repository in Terface.
    • Create repositories that does not provide the all CRUD operations. For example, we can create a repository this provides only the FindAll () method.

The following figure illustrates the benefits of this solution:

The example application of this blog post does do not use this approach because it had only one repository.

Let's move on and summarize "What we learned from" this blog post.

Summary

This blog post has taught us three things:

    • We can create repository interfaces by extending either the crudrepository or the repository interface.
    • We should create our repositories by extending the Repository interface and adding the required methods to the CR Eated Repository interface.
    • If our application have more than one repository, we should create a base repository interface that declares the methods th At is shared by our "concrete" repositories.

The next part of this tutorial describes how we can create a database queries by using query methods.

P.S. You can get the example application of this blog post from Github.

Spring Data JPA Tutorial:crud

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.