4. Spring - Data - Mongo-REST
4. Spring - Data - Mongo-REST
By Vo Van Hai
[email protected]
1
Spring Data - Main modules
https://spring.io/projects/spring-data
2
Spring Data Commons
▸Spring Data Commons is part of the umbrella Spring Data project that
provides shared infrastructure across the Spring Data projects. It contains
technology neutral repository interfaces as well as a metadata model for
persisting Java classes.
▸Primary goals are:
- Powerful Repository and custom object-mapping abstractions
- Support for cross-store persistence
- Dynamic query generation from query method names
- Implementation domain base classes providing basic properties
- Support for transparent auditing (created, last changed)
- Possibility to integrate custom repository code
- Easy Spring integration with custom namespace
3
Accessing data with “pure” JDBC
▸The Spring Framework provides extensive support for working with SQL
databases, from direct JDBC access.
▸Java’s javax.sql.DataSource interface provides a standard method of
working with database connections.
▸Use other objects for execute SQL command:
- Connection
- Statement/PreparedStatement
- ResultSet
- …
4
Configure a Data Source
= ClassPathXmlApplicationContext("dbConfig.xml");
= new AnnotationConfigApplicationContext(DsConfig.class);
5
Execute SQL command
▸The old way with JDBC objects:
6
Example
7
Using JdbcTemplate
8
Using JdbcTemplate
10
Query row(s) with Rows Mapper
Use RowMapper object for mapping one row of the ResultSet to
specific object.
Direct mapping
Mapper class
11
Query with BeanPropertyMapper
12
Spring Data JPA
13
Introduction
▸Spring Data JPA is used to reduce the amount of boilerplate code
required to implement the data access object (DAO) layer.
▸Spring Data JPA is not a JPA provider. It is a library / framework
that adds an extra layer of abstraction on the top of our JPA
provider. If we decide to use Spring Data JPA, the repository layer
of our application contains three layers that are described in the
following figure :
14
Spring Data JPA components
▸Spring Data JPA :- It provides support for
creating JPA repositories by extending the
Spring Data repository interfaces.
▸Spring Data Commons :- It provides the
infrastructure that is shared by the datastore
specific Spring Data projects.
▸JPA Provider :- The JPA Provider implements
the Java Persistence API.
15
Spring Data Repositories Interfaces
16
Spring Data Repositories
17
Working with Spring Data Repositories
Core concepts
▸The central interface in the Spring Data repository abstraction is
Repository. It takes the domain class to manage as well as the identifier
type of the domain class as type arguments.
▸This interface acts primarily as a marker interface to capture the types to
work with and to help you to discover interfaces that extend this one. The
CrudRepository and ListCrudRepository interfaces provide sophisticated
CRUD functionality for the entity class that is being managed.
18
Setting up your project components
19
Configure the DataSource
20
Entities
21
Entity sample
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long deptId;
@OneToMany(mappedBy = "dept",
cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Employee> employees
…
}
@Entity
public class Employee {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long empId;
private String empName;
private Date dob;
@ManyToOne(fetch = FetchType.LAZY)
private Department dept;
…
22
Repositories
▸Use repository for:
- Persist, update and remove one or multiple entities.
- Find one or more entities by their primary keys.
- Count, get, and remove all entities.
- Check if an entity exists with a given primary key.
- …
▸You do not need to write a boilerplate code for CRUD methods.
▸You should specify packages where container finding the repositories.
23
Repositories – Query creation
▸Auto-Generated Queries: Spring Data JPA can auto-generate
database queries based on method names.
▸Auto-generated queries may not be well-suited for complex use
cases. But for simple scenarios, these queries are valuable.
▸Parsing query method names is divided into subject and
predicate.
- The first part (find…By…, exists…By…) defines the subject of the query,
- The second part forms the predicate
• Distinct, And, Or, Between, LessThan, GreaterThan, Like, IgnoreCase,
OrderBy (with Asc, Desc)
24
Repositories – Query creation
▸Example
More: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-
methods.query-creation
25
Queries
▸JPQL
- By default, the query definition uses JPQL.
▸Native
▸Updatable Queries
@Modifying
@Query("update Employee u set u.status = :status where u.empId = :id")
int updateEmployeeStatusForName(@Param("status") Integer status,
@Param("id") Long empId);
26
Query Parameters (1)
28
Query Parameters (2)
▸Collection Parameter
- Use in the case when the where clause of our JPQL or SQL query contains the IN (or
NOT IN) keyword:
Repository
@Query(value = "SELECT e FROM Employee e WHERE e.empName IN :names")
List<Employee> findEmployeeByNameList(
@Param("names") Collection<String> names);
Service
public List<Employee> findEmployeeByNameList(Collection<String>names){
return employeeRepository.findEmployeeByNameList(names);
}
Application
Collection<String> names=List.of("Ty","Teo","Men");
List<Employee> lst = employeeServices.findEmployeeByNameList(names);
lst.stream().iterator().forEachRemaining(employee -> {
System.out.println("------------------- "+ employee.getEmpName());
});
29
Queries – Pagination and Sorting
▸Pagination is often helpful when we have a large dataset, and we want to
present it to the user in smaller chunks.
▸Also, we often need to sort that data by some criteria while paging.
import org.springframework.data.domain.Pageable;
//…
public interface ProductRepository extends
PagingAndSortingRepository<Product, Integer> {
30
Streaming Query Results
31
Demo: Directories structures
entities/models/domains
32
Test application
33
MongoDB Model Implementation
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
38
Connect Server
39
Connect Server -simple
40
Connect Server – abstract config
41
Entities Documentation
42
Repositories
43
Operations
Using Repository
Using MongoTemplate
44
Example structure
45
REST introduction
REST
REST API Web Services
REST Services
RESTful
RESTful API Web Services
RESTful Services
46
REST over HTTP https://www.w3.org/Protocols/rfc2616/rfc2616.txt
Methods Operation
▸HTTP response status codes indicate whether a specific HTTP request has
been successfully completed.
▸Responses are grouped in five classes:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
49
Spring Data REST
Introduction
▸Spring Data REST is itself a Spring MVC application and is designed in such
a way that it should integrate with your existing Spring MVC applications
with little effort.
▸Dependencies
Gradle
Maven
https://docs.spring.io/spring-data/rest/docs/current/reference/html/#reference
50
Basic Settings for Spring Data REST
▸Basic Settings:
51
Basic Settings for Spring Data REST
#1. Setting the Repository Detection Strategy
▸Spring Data REST uses a implementation of the RepositoryDetectionStrategy
interface to determine whether a repository is exported as a REST resource.
▸The RepositoryDiscoveryStrategies inside this interface enumeration includes
the following values:
Name Description
DEFAULT Exposes all public repository interfaces but considers
the exported flag of @(Repository)RestResource.
ALL Exposes all repositories independently of type visibility and
annotations.
ANNOTATED Only repositories annotated
with @(Repository)RestResource are exposed, unless
their exported flag is set to false.
VISIBILITY Only public repositories annotated are exposed.
Table: Repository detection strategies 52
Basic Settings for Spring Data REST
#2. Changing the Base URI
▸By default, Spring Data REST serves up REST resources at the root URI, '/’.
It’s harmful.
▸Change the base(root) path by:
1. Application.properties file: add the instructions:
spring.data.rest.basePath=/api
2. Configuration
53
Basic Settings for Spring Data REST
#2. Changing the Base URI
▸Change the base(root) path by:
3. Implement the RepositoryRestConfigurer interafce
54
Basic Settings for Spring Data REST
#3. Changing Other Spring Data REST Properties
Property Description
basePath the root URI for Spring Data REST
defaultPageSize change the default for the number of items served in a single page
pageParamName change the name of the query parameter for selecting pages
limitParamName change the name of the query parameter for the number of items to
show in a page
sortParamName change the name of the query parameter for sorting
defaultMediaType change the default media type to use when none is specified
55
Repository resources exposure
Fundamentals
▸The core functionality of Spring Data REST is to export resources for Spring
Data repositories. Thus, the core artifact to look at and potentially
customize the way the exporting works is the repository interface.
//@Repository
public interface DepartmentRepository extends JpaRepository<Department, Long> {//…}
- For this repository, Spring Data REST exposes a collection resource at /departments
▸Change the default path by using
@RepositoryRestResource(collectionResourceRel = “dept", path = “dept")
public interface DepartmentRepository extends JpaRepository<Department, Long> {//…}
- /departments now changes to /dept
▸Repository methods exposure
- The resource exposure will follow which methods you have exposed on the
repository → all HTTP resources we can register by default.
- Use @RestResource(exported = false) annotation to limit the exposure
56
Repository resources exposure
Resource Discoverability
▸http://localhost:8080/api
57
Repository resources exposure
Default Status Codes
▸For the resources exposed, we use a set of default status codes:
- 200 OK: For plain GET requests.
- 201 Created: For POST and PUT requests that create new resources.
- 204 No Content: For PUT, PATCH, and DELETE requests when the configuration is set
to not return response bodies for resource updates.
58
Resource Discoverability
Tools
▸Postman
▸CURL
▸The HAL Explorer implementation 'org.springframework.data:spring-data-rest-hal-explorer'
59
Accessing path
/api/collections_name/{id}
/api/collections_name/{id}/attribute
/api/collections_name/?name=value
60
The Collection Resources
▸Parameters
- If the repository has pagination capabilities, the resource takes the following
parameters:
• page: The page number to access (0 indexed, defaults to 0).
• size: The page size requested (defaults to 20).
• sort: A collection of sort directives in the format ($propertyname,)+[asc|desc]?.
▸Supported Media Types
- application/hal+json
- application/json
61
Whitelabel Error Page
62
Transaction
▸Global Transactions
- Global transactions let you work with multiple transactional resources, typically
relational databases and message queues. The application server manages global
transactions through the JTA (Java Transaction API).
- @EnableTransactionManagement
▸Local Transactions
- Local transactions are resource-specific, such as a transaction associated with a JDBC
connection.
- Local transactions may be easier to use but have a significant disadvantage: They
cannot work across multiple transactional resources.
- @Autowired TransactionManager
63
64
Spring HATEOAS 1.0
▸https://docs.spring.io/spring-
hateoas/docs/current/reference/html/
65
66