탑크리에듀(http://www.topcredu.co.kr), 오라클자바커뮤니티(http://ojc.asia)에서 제공하는 스프링, Spring Data JPA 실습 강좌 입니다. 동영상으로 보실분은 홈페이지에 오시면 보실 수 있구요, Spring Data JPA에서 WEB MVC 예제를 스프링 부트 기반에서 작성하고 페이징 기능에 대해 실습한 자료 입니다. 페이스북 페이지(http://www.facebook.com/topcredu.co.kr)에 오셔서 "좋아요"도 부탁드리며 유튜브 페이지(https://www.youtube.com/channel/UCGr9nYZ6hzMim0rQQuSyrDA/playlists?disable_polymer=true) 구독하시면 동영상 강좌들 즉시 확인 가능하십니다.
감사합니다.
(탑크리에듀, Spring Boot, Spring Data JPA MVC 예제 및 페이징,페이지나누기 STS 실습)_스프링/스프링부트/스프링JPA/Querydsl실무학원추천교육
1. 소스코드, 강의자료 및 동영상 다시 보기는 오라클
자바커뮤니티(http://ojc.asia)에서 가능합니다.
2. Spring Data JPA 간단 예제, 페이징 실습
Spring Boot, WEB MVC, Spring Data JPA, Maria DB를 이용하여 간단히 예제를 만들어 보자.
프로젝트 생성
마리아DB 설치는 아래 URL 참조
http://ojc.asia/bbs/board.php?bo_table=LecSpring&wr_id=524
STS에서 File -> New Project -> Spring Starter Project
Name : springjpaexam
Type : MAVEN
Package : jpa
다음화면에서 SQL -> JPA, MySQL, WEB -> Web 선택
src/main/resources/application.properties
spring.datasource.platform=mysql
spring.datasource.sql-script-encoding=UTF-8
spring.datasource.url=jdbc:mysql://localhost/jpa_emp?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=1111
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
#엔티티 클래스를 기반으로 테이블을 자동갱신/생성 하도록
spring.jpa.hibernate.ddl-auto=update
logging.level.jpa=DEBUG
도메인 클래스(Emp.java) – 테이블구조와 동일하다.
package jpa.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Emp {
@Id
6. import org.springframework.boot.autoconfigure.SpringBootApplication;
import jpa.domain.Emp;
import jpa.service.EmpService;
@SpringBootApplication
public class SpringjpaexamApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringjpaexamApplication.class, args);
}
@Autowired
EmpService empService;
// 초기 데이터 생성
public void run(String...args) {
empService.save(new Emp("가길동"));
empService.save(new Emp("하길동"));
empService.save(new Emp("바길동"));
empService.save(new Emp("사길동"));
empService.save(new Emp("라길동"));
empService.save(new Emp("나길동"));
empService.save(new Emp("마길동"));
empService.save(new Emp("정길동"));
empService.save(new Emp("카길동"));
empService.save(new Emp("피길동"));
}
}
[예제 실습]
http://localhost:8080/emp/get/2
http://localhost:8080/emp/save.do?ename=주길동
http://localhost:8080/emp/save/차길동
http://localhost:8080/emp/delete/2
http://localhost:8080/emp/getall
7. Spring Data JPA 페이징(Pageable, PageRequest)
Spring Data JPA에서 페이징은 PagingAndSortingRepository 인터페이스(CrudRepository를 상
속)의 findAll 메소드를 사용하면 간단히 사용할 수 있다. findAll을 호출할 때 인자로
Pageable 인퍼테이스 또는 Pageable 인터페이스 구현체인 PageRequest를 넣어 준다.
public interface PagingAndSortingRepository<T, ID extends Serializable>
extends CrudRepository<T, ID> {
Iterable<T> findAll(Sort sort);
Page<T> findAll(Pageable pageable);
}
PagingAndSortingRepository 인터페이스의 findAll 메소드는 2가지 형태의 파라미터를 지원
한다.
org.springframework.data.domain.Sort : 정렬을 지원
org.springframework.data.domain.Pageable : 페이징을 지원하며 파라미터에 Pageable을 사용하면
리턴형으로 List나 org.springframework.data.domain.Page 사용 한다.
다음과 같이 Controller를 만들면 된다.
public interface EmpRepository<Emp, Integer> extends JpaRepository { }
[컨트롤러 등에서]
[Pageable 예문]
//Pageable을 사용하면 간단하다. 이 컨트롤러 메소드를 호출하는 쪽에서 page, size, sort등
을 파라미터로 던지기만 하면 된다.
//Pageable 인터페이스를 위한 Request Parameter는 다음과 같다.
//page : 검색을 원하는 페이지 번호(0부터 시작)
//size : 한페이지 개수
//sort : 정렬방식(sort=ename, asc&sort=sal, desc)
//localhost:8080/emp/list?page=0&size=3&sort=ename,desc
//////////////////////////////////////////////////////////////////
//첫번째 Page, 한페이지 3개씩, 사원이름 내림차순 정렬
//////////////////////////////////////////////////////////////////
@Autowired
8. EmpService empService;
@RequestMapping(“/list”)
Public Page<Emp> getall(Model model, Pageable pageable) {
model.addAttribute(“list”, empService.findAll(pageable));
return “list”;
}
[PageRequest 예문]
// PageRequest를 사용한다면 파라미터를 넘겨서 다음과 같이 처리하면 된다.
//localhost:8080/list/1 첫페이지
@RequestMapping(“/list”)
public Page<Emp> getall(Model model, @PathVariable Integer pNo,
@PathVariable Integer size) {
// pNo로 넘어오는 페이지를 보이는데 한페이지 size수만큼 사원이름 내림차순
PageRequest request =
new PageRequest(pNo - 1, size, Sort.Direction.DESC, "ename");
return empService.findAll(request);
}
[이미지를 클릭하시면 과정 상세로 이동 합니다.]