이 포스팅은 스프링 부트와 AWS로 혼자 구현하는 웹 서비스
를 보며 공부한 내용을 정리하는 포스팅입니다.
이 게시판에 조회수를 추가해 보자
@Getter
@NoArgsConstructor
@Entity
public class Posts extends BaseTimeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 500, nullable = false)
private String title;
@Column(columnDefinition = "TEXT", nullable = false)
private String content;
private String author;
@Column(columnDefinition = "integer default 0", nullable = false)
private int view;
@Builder
public Posts(String title, String content, String author) {
this.title = title;
this.content = content;
this.author = author;
this.view = view;
}
public void update(String title, String content) {
this.title = title;
this.content = content;
}
}
public interface PostsRepository extends JpaRepository<Posts, Long> {
@Query("SELECT p FROM Posts p ORDER BY p.id DESC")
List<Posts> findAllDesc();
/**
* @Query 어노테이션에서 작성된 조회를 제외한 데이터의 변경이 있는
* 삽입, 수정, 삭제 쿼리 사용 시 필요한 어노테이션
*/
@Modifying
@Query("update Posts p set p.view = p.view + 1 where p.id = :id")
int updateView(@Param("id") Long id);
}
여기서 @Param("id")를 붙혀 주지 않는다면
(Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: For queries with named parameters you need to use provide names for method parameters. Use @Param for query method parameters, or when on Java 8+ use the javac flag -parameters.; nested exception is java.lang.IllegalStateException)
이런 오류가 나기 때문에 붙혀주자.
@RequiredArgsConstructor
@Service
public class PostsService {
private final PostsRepository postsrepository;
@Transactional
public int updateView(Long id){
return postsrepository.updateView(id);
}
}
@GetMapping("/posts/view/{id}")
public String postsView(@PathVariable Long id, Model model) {
PostsResponseDto dto = postsService.findById(id);
postsService.updateView(id); //views ++
model.addAttribute("post",dto);
return "posts-view";
}
잘 동작한다!