0% found this document useful (0 votes)
11 views

4. Spring - Data - Mongo-REST

The document provides an overview of Spring Data, detailing its main modules, including Spring Data Commons and Spring Data JPA, which facilitate data access and management in Java applications. It explains the use of JdbcTemplate for JDBC operations, the structure and functionality of Spring Data repositories, and how to implement RESTful services with Spring Data REST. Additionally, it covers MongoDB integration and various query creation methods, emphasizing the reduction of boilerplate code and the ease of data manipulation.

Uploaded by

trantin1973
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

4. Spring - Data - Mongo-REST

The document provides an overview of Spring Data, detailing its main modules, including Spring Data Commons and Spring Data JPA, which facilitate data access and management in Java applications. It explains the use of JdbcTemplate for JDBC operations, the structure and functionality of Spring Data repositories, and how to implement RESTful services with Spring Data REST. Additionally, it covers MongoDB integration and various query creation methods, emphasizing the reduction of boilerplate code and the ease of data manipulation.

Uploaded by

trantin1973
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Spring Data

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

▸This is the central class in the JDBC core package.


▸It simplifies the use of JDBC and helps to avoid common errors.
▸It executes core JDBC workflow, leaving application code to provide SQL
and extract results.
▸It executes SQL queries or updates, initiating iteration over ResultSets and
catching JDBC exceptions and translating them to the generic, more
informative exception hierarchy defined in the org.springframework.dao
package.

8
Using JdbcTemplate

▸Spring’s JdbcTemplate class is auto-configured, and you can @Autowire


them directly into your own beans.
▸In case of using named parameter, you should use the
NamedParameterJdbcTemplate class

public class StudentJDBCTemplate implements StudentDAO {


private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
@Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public void create(String name, Integer age) {
String SQL = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( SQL, name, age);
System.out.println("Created Record Name = " + name + " Age = " + age);
return;
}
9
Example

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

Using BeanPropertyMapper object will save you a lot of time.

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

▸The power of Spring Data JPA lies in the


repository abstraction that is provided by
the Spring Data Commons project and
extended by the datastore specific sub
projects.
▸We can use Spring Data JPA without
paying any attention to the actual
implementation of the repository
abstraction, but we have to be familiar
with the Spring Data repository interfaces.
These interfaces are described in the
following:

16
Spring Data Repositories

▸Spring Data Commons provides the following repository interfaces:


- Repository — Central repository marker interface. Captures the domain type and the
ID type.
- CrudRepository — Interface for generic CRUD operations on a repository for a specific
type.
- PagingAndSortingRepository — Extension of CrudRepository to provide additional
methods to retrieve entities using the pagination and sorting abstraction.
- QuerydslPredicateExecutor — Interface to allow execution of QueryDSL Predicate
instances. It is not a repository interface.
▸Spring Data JPA provides the following additional repository interfaces:
- JpaRepository — JPA specific extension of Repository interface. It combines all
methods declared by the Spring Data Commons repository interfaces behind a single
interface.
- JpaSpecificationExecutor — It is not a repository interface. It allows the execution of
Specifications based on the JPA criteria API.

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

▸The JDBC driver provides a database specific implementation of the


JDBC API. (MS SQLServer, MySQL, MariaDB,…)
▸The JPA Provider implements the Java Persistence API.
- Hibernate (default JPA implementation provider)
- EclipseLink (you need config yourself)
▸Spring Data JPA hides the used JPA provider behind its repository
abstraction.

19
Configure the DataSource

20
Entities

▸Use @Entity for entity


▸Use @Table if you want to customize your table
▸Should have @Id for the primary-key.
▸Use @Column for customize the column
▸And other annotation if needed
- @OnetoMany
- @ManytoOne
- @OneToOne
- …

21
Entity sample
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long deptId;

@Column(unique = true, nullable = false, length = 150)


private String deptName;

@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)

▸Indexed Query Parameters


- Spring Data will pass method parameters to the query in the same order they appear
in the method declaration

@Query("SELECT e FROM Employee e WHERE e.status = ?1")


List<Employee> findEmployeeByStatus(Integer status);
@Query("SELECT e FROM Employee e WHERE e.status = ?1 and e.empName = ?2")
List<Employee> findEmployeeByStatusAndName(Integer status, String name);
▸Named Parameters
- Each parameter annotated with @Param must have a value string matching the
corresponding JPQL or SQL query parameter name.

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> {

List<Product> findAllByPrice(double price, Pageable pageable);

30
Streaming Query Results

Asynchronous Query Results

31
Demo: Directories structures

entities/models/domains
32
Test application

33
MongoDB Model Implementation

▸MongoDB and Spring Boot can be interacted by using the


MongoTemplate class and MongoRepository interface.
- MongoTemplate — MongoTemplate implements a set of ready-to-use APIs. A good
choice for operations like update, aggregations, and others, MongoTemplate offers
finer control over custom queries.
- MongoRepository — MongoRepository is used for basic queries that involve all or
many fields of the document. Examples include data creation, viewing documents,
and more.

implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'

38
Connect Server

create user if you did not have one

39
Connect Server -simple

40
Connect Server – abstract config

41
Entities Documentation

42
Repositories

▸Repositories in our application should extends the


MongoRepository<T, ID> interface.
▸MongoRepository<T, ID> provides most CRUD operators.
▸We also define more queries using spring naming-method or using
@Query annotaion

43
Operations
Using Repository

Using MongoTemplate

44
Example structure

45
REST introduction

▸REpresentational State Transfer(REST) is lightweight approach for


communicating between applications.
▸REST APIs enable you to develop all kinds of web applications having all
possible CRUD (Create, Retrieve, Update, Delete) operations.
▸Characteristics:
- Language independent
- Platform independent
- Can use any data format (XML and JSON are common).

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

▸REST uses HTTP methods for communication.


- HTTP methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE, CONNECT.
- REST methods: POST, GET, PUT, PATCH, DELETE.

Methods Operation

GET Returns a representational view of a resource's contents and data.

POST Primarily operates on resource collections.


Updates a resource by replacing its content entirely.
PUT It's possible to create a resource with a PUT method (careful: creating
resource without intention.)
Only modifies resource contents. Attention to applying PATCH methods to a
PATCH
whole resource collection.
When a DELETE method targets a single resource, that resource is removed
DELETE
entirely. (Avoid using the DELETE method in a resource collection)
47
REST methods summary
HTTP CRUD Collection Resource (e.g. /users) Single Resouce (e.g.
Method /users/123)
POST Create 201 (Created), ‘Location’ header with Avoid using POST on a
link to /users/{id} containing new ID single resource

GET Read 200 (OK), list of users. Use pagination,


200 (OK), single user. 404
sorting, and filtering to navigate big
(Not Found), if ID not found
lists or invalid
PUT Update/Replace 405 (Method not allowed), unless you 200 (OK) or 204 (No
want to update every resource in the Content). Use 404 (Not
entire collection of resource Found), if ID is not found or
invalid
PATCH Partial 405 (Method not allowed), unless you 200 (OK) or 204 (No
Update/Modify want to modify the collection itself Content). Use 404 (Not
Found), if ID is not found or
invalid
DELETE Delete 405 (Method not allowed), unless you 200 (OK). 404 (Not Found),
want to delete the whole collection — if ID not fou
use with caution
48
Response status

▸HTTP response status codes indicate whether a specific HTTP request has
been successfully completed.
▸Responses are grouped in five classes:

Code range Meaning


100-199 Informational responses

200-299 Successful responses

300-399 Redirection message


400-499 Client error responses
500-599 Server error responses

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

Adding Spring Data REST to a Spring Boot Project

https://docs.spring.io/spring-data/rest/docs/current/reference/html/#reference

50
Basic Settings for Spring Data REST

▸Basic Settings:

- Setting the Repository Detection Strategy

- Changing the Base URI

- Changing Other Spring Data REST Properties

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

maxPageSize change the maximum number of items 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

returnBodyOnCreate change whether a body should be returned when creating a new


entity
returnBodyOnUpdate change whether a body should be returned when updating an entity

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

▸Disable using properties file


- server.error.whitelabel.enabled=false
- Or suing annotation
- @EnableAutoConfiguration(exclude =
{ErrorMvcAutoConfiguration.class})

▸Other fixings: (study later)

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

You might also like