현재
[PP1] jpa + springboot + mysql + react (2)(게시물 작성,수정,삭제) 본문
<Save.jax>
import axios from 'axios';
import { useState } from 'react';
const SaveForm = () => {
const [writer, setWriter] = useState('');
const [pass, setPass] = useState('');
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const save = () => {
if(writer === ''){
alert("작성자를 입력해주십시오.")
return;
}
axios.post('/board/save',{
boardWriter : writer,
boardPass : pass,
boardTitle : title,
boardContent : content
})
.then(res => {
console.log(res.data)
window.location.href="/"
})
.catch( err => {console.log(err)})
}
return(
<div className="SaveForm">
작성자 : <input type="text" onChange={(e) => {
console.log(e.target.value);
setWriter(e.target.value);
}}></input> <br/>
비밀번호 : <input type="password" onChange={(e) => {
console.log(e.target.value);
setPass(e.target.value);
}}></input> <br/>
글 제목 : <input type="text" onChange={(e) => {
console.log(e.target.value);
setTitle(e.target.value);
}}></input> <br/>
글 내용 : <textarea cols={40} rows={10} onChange={(e) => {
console.log(e.target.value);
setContent(e.target.value);
}}></textarea> <br/>
<button onClick={save}> 글 작성</button><br/>
</div>
);
}
export default SaveForm;
- react에서 input안의 value를 변경할때는 setParam을 통해서만 변경할 수 있다.
- axios.post()의 헤더 부분에 변경할 값들을 선언해서 매핑해준다.
<Controller>
package com.board.practice.controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
import com.board.practice.DTO.boardDTO;
import com.board.practice.service.boardService;
import lombok.RequiredArgsConstructor;
@RestController
@RequiredArgsConstructor
@RequestMapping("/board")
public class BoardController {
private final boardService boardService;
@GetMapping("/")
public List<boardDTO> findAll(Model model){
List<boardDTO> boardDtoList = boardService.findAll();
return boardDtoList;
}
@PostMapping("/save")
public String save(@RequestBody boardDTO boardDto){
System.out.println(boardDto);
boardService.save(boardDto);
return "";
}
@GetMapping("/{id}")
public boardDTO findById(@PathVariable Long id){
System.out.println(id);
boardService.updateHits(id);
boardDTO boardDTO = boardService.findById(id);
System.out.println(boardDTO);
return boardDTO;
}
@GetMapping("/update/{id}")
public boardDTO updateForm(@PathVariable Long id){
boardDTO boardDTO = boardService.findById(id);
return boardDTO;
}
@PostMapping("/update/{id}")
public void update(@RequestBody boardDTO boardDTO){
boardDTO receiveBoardDto = findById(boardDTO.getId());
receiveBoardDto.setBoardTitle(boardDTO.getBoardTitle());
receiveBoardDto.setBoardContent(boardDTO.getBoardContent());
boardDTO boardDTO2 = boardService.update(receiveBoardDto);
}
@DeleteMapping("/delete/{id}")
public void delete(@PathVariable Long id){
boardService.delete(id);
}
}
- 객체를 받을때는 RequestBody 어노테이션을 사용해서 받을 수 있다.
- 경로상의 변수를 받기위해서는 PathVariable 변수를 사용한다.
<Service>
package com.board.practice.service;
import org.springframework.stereotype.Service;
import com.board.practice.DTO.boardDTO;
import com.board.practice.entity.boardEntity;
import com.board.practice.repository.BoardRepository;
import jakarta.transaction.Transactional;
import java.util.*;
import lombok.RequiredArgsConstructor;
@Service
@RequiredArgsConstructor
public class boardService {
private final BoardRepository boardRepository;
public List<boardDTO> findAll(){
List<boardEntity> boardEntityList = boardRepository.findAll();
List<boardDTO> boardDtoList = new ArrayList<>();
for ( boardEntity e : boardEntityList){
boardDtoList.add(boardDTO.toBoardDto(e));
}
return boardDtoList;
}
public void save(boardDTO boardDTO){
boardEntity be = boardEntity.toSaveEntity(boardDTO);
System.out.println(be);
boardRepository.save(be);
}
@Transactional // 수동으로 쿼리 건드는 경우에는 무조건 붙임
public void updateHits(Long id) {
boardRepository.updateHits(id);
}
public boardDTO findById(Long id) {
Optional<boardEntity> optionalBoardEntity = boardRepository.findById(id);
if(optionalBoardEntity.isPresent()){
boardEntity boardEntity = optionalBoardEntity.get();
boardDTO abc = boardDTO.toBoardDto(boardEntity);
return abc;
} else {
return null;
}
}
public boardDTO update(boardDTO boardDTO){
boardEntity abc = boardEntity.toUpdateEntity(boardDTO);
boardRepository.save(abc); // jpa는 id가 있으면 update, 없으면 update 한다
return findById(boardDTO.getId());
}
public void delete(Long id){
boardRepository.deleteById(id);
}
}
<boardRepository>
package com.board.practice.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.board.practice.entity.boardEntity;
public interface BoardRepository extends JpaRepository<boardEntity,Long>{
@Modifying // update나 delete작업할 때 붙이는 쿼리
@Query(value = "update boardEntity b set b.boardHits = b.boardHits+1 where b.id = :id")
void updateHits(@Param("id") Long id);
}
'Java > 여러가지프로그램구현연습' 카테고리의 다른 글
| [PP1] jpa + springboot + mysql + react + EC2 + RDS + Docker(6) (최종 배포) (0) | 2024.05.02 |
|---|---|
| [PP1] jpa + springboot + mysql + react (5)(댓글 입력, 댓글 출력) (0) | 2024.04.12 |
| [PP1] jpa + springboot + mysql + react (4)(단일 사진저장, 사진출력 + 다중사진) (0) | 2024.04.10 |
| [PP1] jpa + springboot + mysql + react (3)(게시물 페이징 처리) (0) | 2024.04.09 |
| [PP1] jpa + springboot + mysql (1)(게시물 등록,조회) (0) | 2024.04.01 |