035. Spring Data JPA - dkkahm/study-spring-jpa GitHub Wiki

Repositories

  • CrudRepository
  • PagingAndSortingRepository
  • JpaRepository

Sorting

  • With sort criteria
        Sort sort = Sort.by(Sort.Direction.DESC, "name");
        // sort.and(Sort.by(Sort.Direction.ASC, ...));
        List<Course> resultList = repository.findAll(sort);
        logger.info("{}", resultList);

Pagination

        PageRequest pageRequest = PageRequest.of(0, 3);
        Page<Course> firstPage = repository.findAll(pageRequest);
        logger.info("{}", firstPage.getContent());

with Query

  • JPQL
    @Query("Select c From Course c where name like '%100 Steps'")
    List<Course> courseWith100StepInName();
  • Native
    @Query("Select * From Course c where name like '%100 Steps'", nativeQuery=true)
    List<Course> courseWith100StepInNameUsingNativeQuery();
  • NamedQuery
    @Query(name="query_get_100_Step_courses")
    List<Course> courseWith100StepInNameUsingNamedQuery();

Spring Data REST

  • add dependency
    • compile 'org.springframework.boot:spring-boot-starter-data-rest'
  • Annotate Repository with @RepositoryRestResource
@RepositoryRestResource(path="courses")
public interface CourseSpringDataRepository extends JpaRepository<Course, Long> {
  • Prevent circular reference
    • @JsonIgnore in Entity (com.fasterxml.jackson.annotation.JsonIgnore)
@Entity
public class Course{
    ....
    @ManyToMany(mappedBy = "courses")
    @JsonIgnore
    private List<Student> students = new ArrayList<>();    
⚠️ **GitHub.com Fallback** ⚠️