Knowledge Transfer

Ethickfox kb page with all notes


Project maintained by ethickfox Hosted on GitHub Pages — Theme by mattgraham

Spring Data

Provides a set of common interfaces for interaction with datasources, aspected behaviour and naming convention.

Benefits

Spring Data JPA

Spring Data JPA, part of the larger Spring Data family, makes it easy to easily implement JPA based repositories. This module deals with enhanced support for JPA based data access layers. It makes it easier to build Spring-powered applications that use data access technologies.

@EnableJpaRepositoties

Features

Entity

Entity класс - POJO, который отображает  информацию из связанной таблицы

@Table(name="Books") //table relation
@Column //column relation
@Id // автогенерируемый id
@GeneratedValue // описывает стратегию генерации pk
	Auto // выбор стратегии зависит от типа бд
	Identity // автоматическое увеличение значения предыдущей строчки
	Sequence // c помощью. sequence
	Table // с помощью таблицы со значением
//создание собственного генератора Id
@GenericGenerator(name = "prod-generator",
		parameters = @Parameter(name = "prefix", value = "prod"),
		strategy = "com.baeldung.hibernate.pojo.generator.MyGenerator") 

@EmbeddedId //составной пк
Session //  обертка над подключением к бд с помощью JDBC.

// Отношения между таблицами:
Uni-directional // знает об отношениях только одна сторона
@OneToOne  // тип отношения между объектами: один к одному

Bi-directional // знает об отношениях  обе стороны
MappedBy // связь на второй таблице для Bi-directional, указываем название поля, с которым связать в другом классе
@OneToMany  // тип отношения между объектами: один ко многим
@ManyToMany  - тип отношения между объектами: многие ко многим
// Связь через промежуточную таблицу
@JoinColumn  - столбец, по которому осуществляется связь

Cascade-операции // операции, которые выполняются не только на Entity, но и на связанных с ним Entity

CascadeType // какие операции выполнять на оба метода
	All
	Persist
	Merge
	Refresh

N+1 проблема - два запроса в случае ленивых данных, вместо одного. Можно решить через FetchMode или EntityGraph
fetch = FetchType - тип загрузки:
Eager - загружаются все зависимые сразу
Lazy - загружаются все зависимые при необходимости

Untitled 38.png

2.png

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords

Repository

Реализуется через наследование:

Spring Data 3

Transactions

Spring 3.1 introduces the @EnableTransactionManagement annotation that we can use in a @Configuration class to enable transactional support:

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

JPA in Spring uses JpaTransactionManager, which supports cases when DataSource is used directly, so it allows mixing JPA and JDBC code under one transaction.

@Transactional

Благодаря данной аннотации метод оборачивается с помощью прокси и перед ним запускается транзакция и после него совершается коммит. По этой причине методы того же класса не запустят новую транзакцию. Соответственно только публичные методу работают с данной аннотацией. Можно настраивать, на какие исключения вызывать роллбэк транзакции. Ставится транзакция в слой логики, потому что там как раз осуществляется набор запросов в единую операцию.In case of class level, annotation is applied to every public individual method. Private and Protected methods are Ignored by Spring.

Note that by default, rollback happens for runtime, unchecked exceptions only. The checked exception does not trigger a rollback of the transaction. We can, of course, configure this behavior with the rollbackFor and noRollbackFor annotation parameters.

The annotation supports further configuration as well:

Propagation

TransactionManager

PlatformTransactionMangaer is an interface that extends TransactionManager. It is the central interface in Spring's transaction infrastructure.

JPA can work with following transaction managers:

@Query

Derived Query Methods

Derived method names have two main parts separated by the first By keyword:

List<User> findByName(String name)

The first part — such as find — is the introducer, and the rest — such as ByName — is the criteria.

Spring Data JPA supports findreadquerycount and get.

List<User> findTop3ByAge()

List<User> findByActiveFalse();

List<User> findByNameStartingWith(String prefix);

List<User> findByAgeLessThan(Integer age);

List<User> findByNameOrAge(String name, Integer age);

Dynamic Querying

Criteria API

Untitled 4 2.png

JPASpecificationExecutor

Untitled 5 2.png

Untitled 6 2.png

QueryDSL

Generates classes using plugin

Untitled 7 2.png

All entities will have an implementation starting with Q

Untitled 8 2.png

QueryDslPredicateExecutor

Untitled 9 2.png

Untitled 10 2.png

QueryByExample

JpaRepository already extends QueryByExampleExecutor

Untitled 11 2.png

Untitled 12 2.png

Untitled 13 2.png

Spring Data JDBC

Spring Data JDBC, part of the larger Spring Data family, makes it easy to implement JDBC based repositories. This module deals with enhanced support for JDBC based data access layers. It makes it easier to build Spring powered applications that use data access technologies

Features

Spring Data REST

Spring Data REST is part of the umbrella Spring Data project and makes it easy to build hypermedia-driven REST web services on top of Spring Data repositories.

Spring Data REST builds on top of Spring Data repositories, analyzes your application’s domain model and exposes hypermedia-driven HTTP resources for aggregates contained in the model.

Features

Untitled 14 2.png

Untitled 15 2.png

Untitled 16 2.png

28.png

Untitled 18 2.png

Untitled 19 2.png

Spring Data MongoDB

Spring Data for MongoDB is part of the umbrella Spring Data project which aims to provide a familiar and consistent Spring-based programming model for new datastores while retaining store-specific features and capabilities.

Features

Spring Data Redis

Spring Data Redis, part of the larger Spring Data family, provides easy configuration and access to Redis from Spring applications. It offers both low-level and high-level abstractions for interacting with the store, freeing the user from infrastructural concerns.

Features