spring boot프로젝트 생성 및 mySQL 연동

Ireu·2022년 11월 22일
0

Spring Boot

목록 보기
1/1

fe_react

설치한 패키지
- bootstrap
- axios( for api 통신)
- react-router-dom

vscode에서 확장한 패키지
- reactjs code snippets
- auto import js ~

be_springBoot

1. 프로젝트 세팅 및 MySQL 세팅

https://start.spring.io/ 에서 아래처럼 세팅하고 GENERATE

MySQL에서 'test' database, 'testtable' table 추가,
'title', 'content' 컬럼 추가
데이터 2개정도 생성

2. project 불러온 후, project 우클릭후

Gradle>Refresh Gradle Project 클릭

3. src/main/resources/application.properties파일에 아래 코드 추가

# mySQL
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?&serverTimezone=UTC&autoReconnect=true&allowMultiQueries=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root

#myBatis
mybatis.type-aliases-package: com.example.demo.model
mybatis.mapper-locations=classpath:/mappers//*.xml

#devtools
spring.devtools.livereload.enabled=true

4. src/main/java/com.example.demo/에

src/main/java/com.example.demo/에
controller, model, dto, service package 추가
및 testDTO, testDAO, testController.java 파일 추가

testDTO.java

package com.example.demo.model.dto;
import lombok.Data;

@Data
public class testDTO {
	private String title;
	private String content;
}

testDAO.java

package com.example.demo.model.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.example.demo.model.dto.testDTO;

@Mapper
public interface testDAO {
	public List<testDTO> listTests();
	

}

testController.java

package com.example.demo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.model.dao.testDAO;
import com.example.demo.model.dto.testDTO;

@Controller
public class testController {
	
	@Autowired
	testDAO testDao;
	
	@RequestMapping("/tests")
	public  @ResponseBody Map<String, Object> lists() throws Exception{
		Map<String, Object> obj = new HashMap<>();
		
		List<testDTO> testList = testDao.listTests();
		
		obj.put("list", testList);
		
		return obj;
	}
}

5. src/main/resources/에서

mappers폴더 생성
testMapper.xml 파일 추가

testMapper.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTO Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace ="com.example.demo.model.dao.testDAO">

	<select id="listTests" resultType ="com.example.demo.model.dto.testDTO">
		SELECT
			title, content
		FROM testtable
	</select>
</mapper>
  1. 결과 확인하기

profile
hihi

0개의 댓글