27 Spring - data презентация

Содержание

Слайд 2

Spring data config

org.springframework.data spring-data-jpa 2.0.0.RELEASE

xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

Spring data config org.springframework.data spring-data-jpa 2.0.0.RELEASE http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

Слайд 3

Spring data config

class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

name="jpaVendorAdapter"> org.hibernate.dialect.MySQL55Dialect true true create

Spring data config class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> org.hibernate.dialect.MySQL55Dialect true true create class="org.springframework.orm.jpa.JpaTransactionManager">

Слайд 4

CrudRepository

public interface CatRepository extends CrudRepository {}
Методы сохранения и обновления сущности.

S save(S var1); Iterable saveAll(Iterable var1);
Методы поиска сущности.
Optional findById(ID var1); boolean existsById(ID var1); Iterable findAll(); Iterable findAllById(Iterable var1); long count(); - возвращает количество записей в таблице
Методы удаления сущности.
void delete(ID var1); void delete(T var1); void delete(Iterable var1); void deleteAll();

CrudRepository public interface CatRepository extends CrudRepository {} Методы сохранения и обновления сущности. S

Слайд 5

CrudRepository using

@Data
@NoArgsConstructor
@AllArgsConstructor @Entity public class Cat { @Id @GeneratedValue private Long id;

private String name; private int age; }

public interface CatRepository
extends CrudRepository {}

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/test-data.xml") public class CatTest { @Autowired CatRepository catRepository; @Before public void init() { catRepository.save(new Cat(null, "Matis", 11)); } @Test public void crudRepositoryTest() { System.out.println(catRepository.existsById(1L)); Cat cat = catRepository.findById(1L).orElseGet(null); System.out.println(cat); cat.setAge(12); catRepository.save(cat); System.out.println(cat); catRepository.delete(cat); System.out.println(catRepository.existsById(1L)); } }

CrudRepository using @Data @NoArgsConstructor @AllArgsConstructor @Entity public class Cat { @Id @GeneratedValue private

Слайд 6

Вопросы


Вопросы

Слайд 7

CrudRepository queryed by method name

CrudRepository queryed by method name

Слайд 8

CrudRepository queryed by method name

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/test-data.xml") public class CatCrudTest { @Autowired CatCrudRepository catRepository; @Before public

void init() { catRepository.save(new Cat(null, "Matis", 11)); catRepository.save(new Cat(null, "Proshka", 3)); catRepository.save(new Cat(null, "Tomas", 4)); catRepository.save(new Cat(null, "Geek", 1)); catRepository.save(new Cat(null, "Grom", 2)); catRepository.save(new Cat(null, "Basya", 7)); catRepository.save(new Cat(null, "Masya", 2)); } @Test public void queryMethodTest() { catRepository.findByName("Matis").forEach(System.out::println); catRepository.findByAgeBetweenAndNameEndingWith(3, 8, "a").forEach(System.out::println); catRepository.findByOrderByNameDesc().forEach(System.out::println); } }

public interface CatCrudRepository extends CrudRepository { List findByName(String name); List findByAgeBetweenAndNameEndingWith(
int arg1, int arg2, String nameEndWith); List findByOrderByNameDesc(); }

CrudRepository queryed by method name @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/test-data.xml") public class CatCrudTest { @Autowired CatCrudRepository

Слайд 9

Вопросы


Вопросы

Слайд 10

JpaRepository

public interface CatJpaRepository extends JpaRepository {}

T getOne(ID id); - метод получает

сущность по id.
void flush(); - метод сбрасывает все ожидающие изменения в базу данных.
S saveAndFlush(S var1); - метод сохраняет сущность и мгновенно сбрасывает изменения в базу данных.
Удаление
void deleteInBatch(Iterable var1); - Удаляет данные в пакетной обработке, что означает, что метод создаст один запрос. Предполагается, что после вызова мы очистим EntityManager вызовом метода clear().
void deleteAllInBatch(); - удаляет все сущности при пакетном вызове метода.
Поиск по образцу
Optional findOne(Example example);
List findAll(Example var1);
List findAll(Example var1, Sort var2);

JpaRepository public interface CatJpaRepository extends JpaRepository {} T getOne(ID id); - метод получает

Слайд 11

JpaRepository using

@Data
@NoArgsConstructor
@AllArgsConstructor @Entity public class Cat { @Id @GeneratedValue private Long id; private

String name; private int age; }

public interface CatJpaRepository
extends JpaRepository {}

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/test-data.xml") public class CatJpaTest { @Autowired CatJpaRepository catRepository; @Before public void init() { catRepository.save(new Cat(null, "Matis", 11)); catRepository.save(new Cat(null, "Proshka", 3)); catRepository.save(new Cat(null, "Tomas", 4)); catRepository.save(new Cat(null, "Geek", 1)); catRepository.save(new Cat(null, "Grom", 2)); catRepository.save(new Cat(null, "Basya", 7)); catRepository.save(new Cat(null, "Masya", 2)); } @Test public void jpaRepositoryTest() { System.out.println(catRepository.existsById(1L)); Cat cat = catRepository.getOne(1L); System.out.println(cat); cat.setName("New name" +cat.getName()); catRepository.saveAndFlush(cat); Cat newCat = catRepository.getOne(1L); System.out.println(newCat); } }

JpaRepository using @Data @NoArgsConstructor @AllArgsConstructor @Entity public class Cat { @Id @GeneratedValue private

Слайд 12

Вопросы


Вопросы

Слайд 13

JpaRepository. Query annotated @Query.

public interface DepartmentRepository extends JpaRepository { @Query("select distinct(d) from

Department d
join d.employees e where e.firstName = ?1") List getByJoinCondition(String name); @Query("select d from Department d join d.employees e
where e.age = (select max(e.age) from Employee e)") List getByMaxAge(); @Query("select d from Department d
join d.employees e where e.lastName = :lastName") List getByEmployeesLastName(@Param("lastName") String familyName); @Query(value = " select d.* from Department d" + " left join Employee e on d.id = e.department_id" + " where e.firstName = ?1", nativeQuery = true) List getByJoinConditionNative(String name); }

@Test public void queryTest() { departmentRepository.getByJoinCondition("Sasha").forEach(System.out::println);} @Test public void queryParamTest() { departmentRepository.getByEmployeesLastName("Shi").forEach(System.out::println);} @Test public void nativeQueryTest() {
departmentRepository.getByJoinConditionNative("Yana").forEach(System.out::println);} @Test public void maxAgeTest() { departmentRepository.getByMaxAge().forEach(System.out::println); }

JpaRepository. Query annotated @Query. public interface DepartmentRepository extends JpaRepository { @Query("select distinct(d) from

Слайд 14

Вопросы


Вопросы

Слайд 15

PagingAndSortingRepository.

public interface PagingAndSortingRepository
extends CrudRepository { Iterable findAll(Sort var1); Page findAll(Pageable

var1); }

PagingAndSortingRepository. public interface PagingAndSortingRepository extends CrudRepository { Iterable findAll(Sort var1); Page findAll(Pageable var1); }

Слайд 16

PagingAndSortingRepository.

public interface EmployeePagingRepository extends PagingAndSortingRepository { Page findByDepartmentIdIn(List ids, Pageable pageable); Page

findByDepartmentId(Long id, Pageable pageable); Page findByFirstName(String name, Pageable pageable); }

@Test public void pageableTest() { List ids = Stream.of(2L, 3L, 4L).collect(Collectors.toList()); Page employeesPage = employeeRepository.findByDepartmentIdIn(ids, PageRequest.of(1, 3, Sort.Direction.DESC, "age")); employeesPage.getContent().forEach(System.out::println); employeesPage = employeeRepository.findByFirstName("Sasha",
PageRequest.of(0, 2, Sort.Direction.DESC, "age")); employeesPage.getContent().forEach(System.out::println); employeesPage = employeeRepository.findAll(PageRequest.of(0, 2, Sort.Direction.DESC, "age")); employeesPage.getContent().forEach(System.out::println); employeesPage = employeeRepository.findByDepartmentId(2L,
PageRequest.of(0, 2, Sort.Direction.DESC, "age")); employeesPage.getContent().forEach(System.out::println); employeeRepository.findAll(new Sort(Sort.Direction.DESC, "department.name"))
.forEach(System.out::println); }

PagingAndSortingRepository. public interface EmployeePagingRepository extends PagingAndSortingRepository { Page findByDepartmentIdIn(List ids, Pageable pageable); Page

Слайд 17

Вопросы


Вопросы

Слайд 18

Find by example

public interface QueryByExampleExecutor { Optional findOne(Example var1);

extends T> Iterable findAll(Example var1); Iterable findAll(Example var1, Sort var2); Page findAll(Example var1, Pageable var2); long count(Example var1); boolean exists(Example var1); }

@Test public void findByExampleTest() { System.out.println(departmentRepository.findOne(
Example.of(new Department(null, "Бухгалтерия", null)))); List departments = departmentRepository.findAll( Example.of(new Department(null, "терия", null), ExampleMatcher.matching() .withIgnoreCase() .withStringMatcher(ExampleMatcher.StringMatcher.ENDING))); departments.forEach(System.out::print); }

Find by example public interface QueryByExampleExecutor { Optional findOne(Example var1); Iterable findAll(Example var1);

Слайд 19

Вопросы


Вопросы

Слайд 20

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

Документация

https://docs.spring.io/spring-data/jpa/docs/current/reference/html Документация

Имя файла: 27-Spring---data.pptx
Количество просмотров: 117
Количество скачиваний: 0