Ethickfox kb page with all notes
Provides a set of common interfaces for interaction with datasources, aspected behaviour and naming convention.
Benefits
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
Sophisticated support to build repositories based on Spring and JPA
Support for Querydsl predicates and thus type-safe JPA queries
List<Person> persons = queryFactory.selectFrom(person)
.where(
person.firstName.eq("John"),
person.lastName.eq("Doe"))
.fetch();
Transparent auditing of domain class
Pagination support, dynamic query execution, ability to integrate custom data access code
Validation of @Query annotated queries at bootstrap time
Support for XML based entity mapping
JavaConfig based repository configuration by introducing @EnableJpaRepositories.
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 - загружаются все зависимые при необходимости


https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords
Реализуется через наследование:
Spring Data 3
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.
Благодаря данной аннотации метод оборачивается с помощью прокси и перед ним запускается транзакция и после него совершается коммит. По этой причине методы того же класса не запустят новую транзакцию. Соответственно только публичные методу работают с данной аннотацией. Можно настраивать, на какие исключения вызывать роллбэк транзакции. Ставится транзакция в слой логики, потому что там как раз осуществляется набор запросов в единую операцию.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
PlatformTransactionMangaer is an interface that extends TransactionManager. It is the central interface in Spring's transaction infrastructure.
JPA can work with following transaction managers:
JpaTransactionManager – recommended when working with one database and one Entity Manager

JtaTransactionManager – recommended when working with multiple databases and Entity Managers, or when working with multiple databases and other transactional resources, for example one transaction needs to span Database and JMS Topic

Spring JPA can automatically generate the ORDER_BY using the Sort parameter. This is mostly used on the occasions that you might want to order the query in ascending order or descending order.
@Query("select s from Student s where s.age = ?15")
List<Student> findStudentByAgeAndSorted(int age, Sort sort);
@Query Example with Named Parameters
@Query(value = "SELECT * FROM Student WHERE age = :age
and name= :name", nativeQuery = true)
Book findStudentByAgeAndStudentNameNative(@Param("age") int age,
@Param("name") String name);
Native SQL Select @Query with Index Parameters
@Query(value = "SELECT * FROM Student WHERE age = ?15
and name = ? Megan Alex ", nativeQuery =true)
Book findStudentByAgeAndNameNative(String age, String studentName);
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 find, read, query, count 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);



Generates classes using plugin

All entities will have an implementation starting with Q

QueryDslPredicateExecutor


JpaRepository already extends QueryByExampleExecutor



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
NamingStrategy.@Query annotations.@EnableJdbcRepositories.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.
ApplicationEvents.





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.
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.
Repository interfaces including support for custom query methods using @EnableRedisRepositories.