Creating a Spring Data repository

Spring Data provides a consistent Spring-based programming model to access data. It abstracts away the low-level boilerplate details and can be used to access a wide variety of data stores including the SQL (relational and non-relational) database, map-reduce frameworks, cloud-based data services, and so on. The Spring Data repository basically implements the data access layer and provides abstract access to interact with the underlying data store.

We will configure the Spring Data repository to interact with MongoDB. The first step is to create an entity object (domain model). Spring Data allows accessing data in an object-oriented way, so first we need to define the entity class and provide the necessary mapping with the persistence model. An entity class can be created as follows:

@Document(collection="Student")
public class Student {
@Id
@JsonIgnore
private String id;

@NotNull(message="Roll no can not be empty")
private Integer rollNo;

@NotNull(message="Name can not be empty")
private String name;

@NotNull(message="Standard can not be empty")
private Integer standard;

//.. getter and setter
}

This POJO class represents the student entity in MongoDB with the @Document annotation. You need to give the same collection name here that we created in MongoDB. The attribute ID will be autogenerated by MongoDB and can be considered as a primary key for the Student entity so it is marked with the @Id annotation.

Next add a Spring Data repository. Spring provide repository support for specific data stores. For MongoDB, the Spring Data repository should looks as follows:

@Repository
public interface StudentMongoRepository extends ReactiveMongoRepository<Student, String>{
public Mono<Student> findByRollNo(Integer rollNo);
public Mono<Student> findByName(String name);
}

Spring Data provides the ReactiveMongoRepository interface that can be extended to define a custom repository. It is of the Student type, which is an object entity type when we want to interact with MongoDB and String , which represent the primary key (ID in our case).

The Spring Data repository provides a nice feature called the query method, which is used to access data based on specific column or  attribute values by following a certain naming convention. For example, findByName(String name) will return  StudentData with the matching name. Spring Data provides underlying implementation of these methods out of the box. For simplicity, we kept just two methods.

To make sure the Spring application connects to MongoDB, we need to add the following properties in the application.properties file:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=StudentData

This is equivalent to defining connection properties in a database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.30.253