Controller
TestController에서 PostMapping으로 insert하기 위해 아래 코드를 추가했다
@PostMapping(value = "/")
public String insertTest(@RequestBody TestDTO testDTO) throws Exception {
log.debug("insertTest");
return testService.insertTest(testDTO);
}
Service
Controller에서 Service를 호출하면 Service에서 아래 비즈니스 로직을 처리한다
public String insertTest(TestDTO testDTO) throws Exception {
// testDTO db에 insert
int result = testDAO.insertTest(testDTO);
return result + " rows inserted";
}
DAO
이제 DAO에서 데이터와 관련된 작업(insert)을 정의한다
@Repository
public interface TestDAO {
List<TestDTO> getTestList();
int insertTest(TestDTO testDTO);
}
Mapper
이제 실행할 Insert쿼리가 있는 TestMapper.xml 파일이다.
Mapper namespace 와 id로 insertTest를 호출하여 아래 쿼리를 실행한다!
<insert id="insertTest" parameterType="kr.ac.daegu.springbootapi.test.model.TestDTO">
INSERT INTO Test (id, name) values (#{num}, #{name})
<!--insert into test(id,name) select max(id) + 1, #{name} from test-->
<!--위 쿼리도 실행된다. sql로 id count+1-->
</insert>
실행
사진이 작아서 잘 안 보일수도 있지만.. test/ 폴더와 board/ 폴더를 각각 insert를 구현하는 post
Table안의 데이터를 보여주는 Get방식으로 분리시켰다
Body에서 raw와 JSON을 선택하고! post방식으로 Send한다.
num은 입력하지 않아도 자동으로 증가되게 AUTO_INCREMENT 를 사용하였다!
Service에서 비즈니스 로직을 수행하고 rows inserted가 출력된 것이 보인다
Board Table
Board Table에서도 위와 같은 방법을 사용하여 데이터를 insert했다.
이전에 jsp에서 사용하던 테이블이라 칼럼이 꽤 많다.
최대한 안전하게.. 이번에는 sql쿼리로 자동으로 id값을 증가시켰다.
<insert id="insertBoard" parameterType="kr.ac.daegu.springbootapi.board.model.BoardDTO">
insert into board (id,author, subject, content, writeDate, writeTime, readCount, commentCount, password, pid, `depth`,porder)
select max(id) + 1, #{author}, #{subject}, #{content}, CURDATE(), CURTIME(), 0, 0, #{password},max(id) + 1,0,0
from board
</insert>
board에서도 똑같이 insertBoard를 호출하여 쿼리를 실행!!
'Spring Boot > Spring Boot' 카테고리의 다른 글
41: Springboot (Delete-board) (0) | 2021.10.01 |
---|---|
40: Springboot (Read-board) (0) | 2021.10.01 |
37 : Springboot (Board - Mybatis) (0) | 2021.09.29 |
36-2 : Springboot (Service) (0) | 2021.09.29 |
36 : Springboot (MyBatis를 이용하여 MySQL 연동) (0) | 2021.09.28 |