• filter를 사용할 땐 검색할 때만!!!(페이지 리스트 찾을 때) → 시도 때도 없이 찾으면 속도가 느려진다..
  • html은 포맷팅(ctrl+d)을 피하자!! 가독성이 떨어진다

"URL 경로에 변수를 넣어주는 것" "RESTful 서비스의 URI 형태"

 

사용법

@GetMapping({"/edit", "/edit/{id}"})
  public String edit(@PathVariable(required = false) Integer id, Model model) {

위와 같이 GetMapping에서 id가 필요할 경우에만 사용할 땐 (required = false)를 붙인다.

그럼 id가 들어오면 /edit/{id}를 주고 id가 없으면 /edit을 준다.

 

 @GetMapping("/read/{id}")
  public String read(@PathVariable Integer id, Model model) {

위는 id가 필수적으로 필요하다.

 

❗ id가 없을 때도 잘 받기 위해선 view 쪽에 hidden input으로 id를 설정해주면 알아서 처리해줌... ❗

<form method="post" th:action="|@{/project/save}|" th:object="${project}">
        <input th:field="*{id}" type="hidden"/>

/repository/support안에 impl 파일들

public class ProjectRepositoryImpl extends QuerydslRepositorySupport implements
    CustomProjectRepository {

위와 같이 QuerydslRepositorySupport를 extends 한다. 안에 필요한 함수들을 구현해주면 된다.

 

 @Override
  public Page<Project> findAllByFilter(Pageable pageable, ProjectFilter filter) {
    BooleanBuilder builder = new BooleanBuilder();

    if (!StringUtils.isBlank(filter.getDate())) {
      builder.and(project.date.containsIgnoreCase(filter.getDate()));
    }
    if (!StringUtils.isBlank(filter.getTitle())) {
      builder.and(project.title.containsIgnoreCase(filter.getTitle()));
    }
    if(!StringUtils.isBlank(filter.getAddress())){
      builder.and(project.address.containsIgnoreCase(filter.getAddress()));
    }
    if(!StringUtils.isBlank(filter.getTechnology())){
      builder.and(project.technology.containsIgnoreCase(filter.getTechnology()));
    }
    if(!StringUtils.isBlank(filter.getAddress())){
      builder.and(project.purpose.containsIgnoreCase(filter.getPurpose()));
    }

    final JPQLQuery<Project> query = from(project).where(builder);

    List<Project> result = getQuerydsl().applyPagination(pageable, query).fetch();

    return new PageImpl<>(result,pageable,query.fetchCount());

  }

위와 같이 원하는 정보들을 모아서 paging 해준다.

 

물론 /repository/custom 과 /repository 설정은 기본적으로 해준 상태에서 진행해야한다!!!

 

그 후 controller에 pageable 활용

  @GetMapping("")
  public String list(Model model, Pageable pageable, ProjectFilter filter) {

    model.addAttribute("projectList", projectService.findAllByFilter(pageable, filter));
    model.addAttribute("filter", filter);
    return "project/list";
  }

 

❗ paging 원리에 대해선 나중에 다뤄봐야겠다.. ❗

'Web > Spring' 카테고리의 다른 글

[ERROR] 유의해야 할 점  (0) 2021.08.06
[Annotation] @PathVariable  (0) 2021.08.06
[배경] JPA vs JDBC, JPA vs Mybatis, JPA vs Spring Data JPA  (0) 2021.08.06
[설정] 자동망치 기능  (0) 2021.08.06
[설정] application.properties  (0) 2021.08.04

JDBC

  • JDBC는 DB에 접근하고, SQL을 날릴 수 있게 해주는 자바의 표준 API
  • DriverMAnager를 사용해 각 드라이버들을 로딩, 해제한다.

[출처] https://skyblue300a.tistory.com/7

JPA

  • JPA는 자바 진영 ORM의 API 표준 명세
  • 내부적으로 JDBC를 사용

[출처] https://skyblue300a.tistory.com/7

Spring JDBC(SQL Mapper → MyBatis)

  • JDBC에서 DriveManager가 하는 일들을 JdbcTemplate에게
  • 쿼리문을 사용한다.

[출처] https://skyblue300a.tistory.com/7

Spring Data JDBC

  • Spring data는 Spring에서 DB를 쉽게 다루기 위해 시작한 프로젝트
  • @Query 어노테이션 사용

[출처] https://skyblue300a.tistory.com/7

Hibernate

  • JPA를 구현한 프레임워크
  • Spring은 기본 JPA vendor로 Hibernate를 사용

[출처] https://skyblue300a.tistory.com/7

정리

 

 

❗ 나는 Hibernate를 사용해 구현할 예정..!!!! ❗

'Web > Spring' 카테고리의 다른 글

[Annotation] @PathVariable  (0) 2021.08.06
[Pageable] 페이징 처리 - 기본  (0) 2021.08.06
[설정] 자동망치 기능  (0) 2021.08.06
[설정] application.properties  (0) 2021.08.04
[CRUD] R구현  (0) 2021.08.02

자동망치 기능

  • view쪽을 수정하고 재실행하지 않고 망치를 눌러서 수정된 화면을 확인할 수 있다.(ctrl+shift+r)

intelliJ 위쪽 메뉴바

초록색 망치모양을 클릭한 후 화면에서 ctrl+shift+r을 눌러 새로고침한다.

 

자동망치 설정

  • 의존성 추가
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <scope>runtime</scope>
      <optional>true</optional>
    </dependency>

 

  • properties 설정
 <!--- application.yml--->
    devtools:
      livereload:
        enabled: false
      add-properties: false
      restart:
        enabled: false
        
<!--- application-local.yml--->
    devtools:
      livereload:
        enabled: true
      add-properties: true
      restart:
        enabled: false

 

  • Edit Configuration

초록 망치 옆 네모칸 클릭

Active profiles를 local로 설정해준다

'Web > Spring' 카테고리의 다른 글

[Pageable] 페이징 처리 - 기본  (0) 2021.08.06
[배경] JPA vs JDBC, JPA vs Mybatis, JPA vs Spring Data JPA  (0) 2021.08.06
[설정] application.properties  (0) 2021.08.04
[CRUD] R구현  (0) 2021.08.02
[CRUD] C구현  (0) 2021.08.02

CRUD

  • Create (INSERT)
  • Read (SELECT)
  • Update (UPDATE)
  • Delete (DELETE)

Read 구현

필요한 것

  • DB table에서 원하는 내용을 꺼내올 것
  • list 화면에 내용들을 list로 보여줌
  • list들 중 하나를 클릭하면 read화면이 떠서 볼 수 있게

 

❗ C구현에서 했던 filter와 service, repository들을 그대로 활용할 예정 ❗

먼저 list화면을 구현

<!DOCTYPE HTML>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">

<head>
  <th:block th:replace="fragments/head :: head"></th:block>
  <link rel="stylesheet" th:href="@{/static/assets/css/project-list.css}" type="text/css"/>
  <style>
    h2, p {
      font-weight: bold;
    }
    a {
      text-decoration: none;
      color: #777777;
    }
  </style>
</head>

<body class="is-preload">
<div id="wrapper">
  <th:block th:replace="fragments/top :: top"></th:block>
  <div id="main">
    <article id="work" class="panel">
      <header>
        <h2>Project</h2>
      </header>
      <p>
        A field of interest :
        <span style="font-weight: lighter">Cloud(AWS, OpenStack), WEB(Spring), DevOps</span>
      </p>

      <table class="type09">
        <thead>
        <tr>
          <th scope="col">No.</th>
          <th scope="col">Progress Date</th>
          <th scope="col">Project Title</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="p: ${projectList}">
          <td scope="row" style="width: 50px"><a th:text="${p.id}" th:href="|@{/project/read}/${p.id}|"></a> </td>
          <td><a th:text="${p.date}" th:href="|@{/project/read}/${p.id}|"></a> </td>
          <td><a th:text="${p.title}" th:href="|@{/project/read}/${p.id}|"></a> </td>
        </tr>
        </tbody>
      </table>
      <a class="addButton" th:text="|ADD|" th:href="|@{/project/edit}|"></a>
    </article>
  </div>
</div>
<th:block th:replace="fragments/footer :: footer"></th:block>
<th:block th:replace="fragments/common-script :: common-script"/>
</body>
</html>

 

읽을 read화면도 구현

<!DOCTYPE HTML>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">

<head>
  <th:block th:replace="fragments/head :: head"></th:block>
  <link rel="stylesheet" th:href="@{/static/assets/css/project-read.css}" type="text/css"/>
  <style>
    h2 {
      font-weight: bold;
    }
  </style>
</head>

<body class="is-preload">
<div id="wrapper">

  <th:block th:replace="fragments/top :: top"></th:block>
  <div id="main">
    <article id="work" class="panel" th:object="${project}">
      <h2>Project</h2>
      <div class="mb-3">
        <h4 class="title" th:text="*{title}"></h4>
      </div>
      <div class="mb-3">
        <h5 class="date" th:text="*{date}"></h5>
      </div>
      <hr class="one">
      <div class="mb-3">
        <h5 class="purpose" th:text="*{purpose}"></h5>
      </div>
      <hr class="two">
      <div class="mb-3">
        <h5 class="technology" th:text="*{technology}"></h5>
      </div>
      <hr class="two">
      <div class="mb-3">
        <h5 class="address" th:text="*{address}"></h5>
      </div>

    </article>
  </div>
</div>
<th:block th:replace="fragments/footer :: footer"></th:block>
<th:block th:replace="fragments/common-script :: common-script"/>
</body>
</html>

 

이 화면들을 띄워줄 controller 구현

@Controller
@RequiredArgsConstructor
@RequestMapping("/project")
public class ProjectController {

 @NonNull
  private final ProjectService projectService;

  @GetMapping("")
  public String list(Model model, Pageable pageable, ProjectFilter filter) {

    model.addAttribute("projectList", projectService.findAllByFilter(pageable, filter));
    model.addAttribute("filter", filter);
    return "project/list";
  }
  
   @GetMapping("/read/{id}")
  public String read(@PathVariable Integer id, Model model) {

    Project project = projectService.findById(id).orElseThrow(DataNotFoundException::new);
    model.addAttribute("project",project);

    return "project/read";
  }
}

여기까지 구현하면 CR구현이 완성되었다!

list 화면
read 화면

 

❗ 코드 관련 문법이나 필요한 내용들은 따로 정리할 예정이며 UD는 천천히 구현해볼 예정이다! ❗

'Web > Spring' 카테고리의 다른 글

[설정] 자동망치 기능  (0) 2021.08.06
[설정] application.properties  (0) 2021.08.04
[CRUD] C구현  (0) 2021.08.02
[JPA] 데이터베이스 생성 또는 초기화  (0) 2021.08.02
[ERROR] Pageable import  (0) 2021.08.02

+ Recent posts