Похожие презентации:
Spring Data
1.
Spring DataАвтор: Юлий Слабко
2. Spring data config
<dependencies><dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
</dependencies>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
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">
<jpa:repositories base-package="by.academy.it.springdata.repository" />
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/spring_data"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="yuli"/>
<property name="initialSize" value="5"/>
<property name="maxTotal" value="20"/>
</bean>
2
3. Spring data config
<bean id="entityManagerFactory"class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="by.academy.it.springdata.entities"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL55Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager“
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven/>
</beans>
3
4. CrudRepository
public interface CatRepository extends CrudRepository<Cat, Long> {}Методы сохранения и обновления сущности.
<S extends T> S save(S var1);
<S extends T> Iterable<S> saveAll(Iterable<S> var1);
Методы поиска сущности.
Optional<T> findById(ID var1);
boolean existsById(ID var1);
Iterable<T> findAll();
Iterable<T> findAllById(Iterable<ID> var1);
long count(); - возвращает количество записей в таблице
Методы удаления сущности.
void delete(ID var1);
void delete(T var1);
void delete(Iterable<? extends T> var1);
void deleteAll();
4
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<Cat, Long> {}
@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));
}
}
5
6.
Вопросы6
7. CrudRepository queryed by method name
Ключевое словоAnd
Образец метода
findByLastnameAndFirstname
JPQL пример
where x.lastname=?1 and x.firstname=?2
Or
findByLastnameOrFirstname
where x.lastname=?1 or x.firstname=?2
Is,Equals
findByFirstname, findByFirstnameIs,
findByFirstnameEquals
where x.firstname = ?1
Between
LessThan
LessThanEqual
GreaterThan
GreaterThanEqual
After
Before
IsNull
IsNotNull, NotNull
findByStartDateBetween
findByAgeLessThan
findByAgeLessThanEqual
findByAgeGreaterThan
findByAgeGreaterThanEqual
findByStartDateAfter
findByStartDateBefore
findByAgeIsNull
findByAge(Is)NotNull
where
where
where
where
where
where
where
where
where
Like
NotLike
StartingWith
findByFirstnameLike
findByFirstnameNotLike
findByFirstnameStartingWith
where x.firstname like ?1
where x.firstname not like ?1
where x.firstname like ?1 (parameter bound with appended %)
EndingWith
findByFirstnameEndingWith
where x.firstname like ?1 (parameter bound with prepended %)
Containing
findByFirstnameContaining
where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy
findByAgeOrderByLastnameDesc
where x.age = ?1 order by x.lastname desc
Not
In
NotIn
True
False
IgnoreCase
findByLastnameNot
findByAgeIn(Collection<Age> ages)
findByAgeNotIn(Collection<Age> age)
findByActiveTrue()
findByActiveFalse()
findByFirstnameIgnoreCase
where
where
where
where
where
where
x.startDate between ?1 and ?2
x.age < ?1
x.age <= ?1
x.age > ?1
x.age >= ?1
x.startDate > ?1
x.startDate < ?1
x.age is null
x.age not null
x.lastname <> ?1
x.age in ?1
x.age not in ?1
x.active = true
x.active = false
UPPER(x.firstame) = UPPER(?1)
7
8. CrudRepository queryed by method name
public interface CatCrudRepository extends CrudRepository<Cat, Long> {List<Cat> findByName(String name);
List<Cat> findByAgeBetweenAndNameEndingWith(
int arg1, int arg2, String nameEndWith);
List<Cat> findByOrderByNameDesc();
}
@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);
}
}
8
9.
Вопросы9
10. JpaRepository
public interface CatJpaRepository extends JpaRepository<Cat, Long> {}T getOne(ID id); - метод получает сущность по id.
void flush(); - метод сбрасывает все ожидающие изменения в базу
данных.
<S extends T> S saveAndFlush(S var1); - метод сохраняет сущность и
мгновенно сбрасывает изменения в базу данных.
Удаление
void deleteInBatch(Iterable<T> var1); - Удаляет данные в пакетной
обработке, что означает, что метод создаст один запрос.
Предполагается, что после вызова мы очистим EntityManager вызовом
метода clear().
void deleteAllInBatch(); - удаляет все сущности при пакетном
вызове метода.
Поиск по образцу
<S extends T> Optional<S> findOne(Example<S> example);
<S extends T> List<S> findAll(Example<S> var1);
<S extends T> List<S> findAll(Example<S> var1, Sort var2);
10
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<Cat, Long> {}
@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);
}
}
11
12.
Вопросы12
13. JpaRepository. Query annotated @Query.
public interface DepartmentRepository extends JpaRepository<Department, Long> {@Query("select distinct(d) from Department d
join d.employees e where e.firstName = ?1")
List<Department> getByJoinCondition(String name);
@Query("select d from Department d join d.employees e
where e.age = (select max(e.age) from Employee e)")
List<Department> getByMaxAge();
@Query("select d from Department d
join d.employees e where e.lastName = :lastName")
List<Department> getByEmployeesLastName(@Param("lastName") String familyName);
@Query(value = "
"
"
List<Department>
select d.* from Department d" +
left join Employee e on d.id = e.department_id" +
where e.firstName = ?1", nativeQuery = true)
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);
}
13
14.
Вопросы14
15. PagingAndSortingRepository.
public interface PagingAndSortingRepository<T, ID>extends CrudRepository<T, ID> {
Iterable<T> findAll(Sort var1);
Page<T> findAll(Pageable var1);
}
15
16. PagingAndSortingRepository.
public interface EmployeePagingRepository extends PagingAndSortingRepository<Employee, Long> {Page<Employee> findByDepartmentIdIn(List<Long> ids, Pageable pageable);
Page<Employee> findByDepartmentId(Long id, Pageable pageable);
Page<Employee> findByFirstName(String name, Pageable pageable);
}
@Test
public void pageableTest() {
List<Long> ids = Stream.of(2L, 3L, 4L).collect(Collectors.toList());
Page<Employee> 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);
}
16
17.
Вопросы17
18. Find by example
public interface QueryByExampleExecutor<T> {<S extends T> Optional<S> findOne(Example<S> var1);
<S extends T> Iterable<S> findAll(Example<S> var1);
<S extends T> Iterable<S> findAll(Example<S> var1, Sort var2);
<S extends T> Page<S> findAll(Example<S> var1, Pageable var2);
<S extends T> long count(Example<S> var1);
<S extends T> boolean exists(Example<S> var1);
}
@Test
public void findByExampleTest() {
System.out.println(departmentRepository.findOne(
Example.of(new Department(null, "Бухгалтерия", null))));
List<Department> departments = departmentRepository.findAll(
Example.of(new Department(null, "терия", null), ExampleMatcher.matching()
.withIgnoreCase()
.withStringMatcher(ExampleMatcher.StringMatcher.ENDING)));
departments.forEach(System.out::print);
}
18
19.
Вопросы19
20.
Документацияhttps://docs.spring.io/springdata/jpa/docs/current/reference/html
20
21.
Спасибо за внимание21