스프링 부트 (STS)를 이용한 학생 정보 관리 시스템 구축 예제
1. 프로젝트 설정
- **STS (Spring Tool Suite)**를 실행하고 새로운 Spring Boot 프로젝트를 생성합니다.
- 프로젝트 이름: StudentManagement
- 패키지 이름: com.example.student
- 의존성: Spring Web, Spring Data JPA, H2 Database, MyBatis Framework
2. VO (Value Object) 클래스 생성
- Student.java
Java
package com.example.student.vo;
public class Student {
private int id; // 학번
private String name; // 이름
private String phone; // 전화번호
// 생성자, Getter/Setter
}
3. Mapper 인터페이스 생성
- StudentMapper.java
Java
package com.example.student.mapper;
import com.example.student.vo.Student;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface StudentMapper {
List<Student> selectAllStudents();
Student selectStudentById(int id);
void insertStudent(Student student);
void updateStudent(Student student);
void deleteStudent(int id);
}
4. Service 클래스 생성
- StudentService.java
Java
package com.example.student.service;
import com.example.student.mapper.StudentMapper;
import com.example.student.vo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentService {
@Autowired
private StudentMapper studentMapper;
public List<Student> getAllStudents() {
return studentMapper.selectAllStudents();
}
public Student getStudentById(int id) {
return studentMapper.selectStudentById(id);
}
public void createStudent(Student student) {
studentMapper.insertStudent(student);
}
public void updateStudent(Student student) {
studentMapper.updateStudent(student);
}
public void deleteStudent(int id) {
studentMapper.deleteStudent(id);
}
}
5. Controller 클래스 생성
- StudentController.java
Java
package com.example.student.controller;
import com.example.student.service.StudentService;
import com.example.student.vo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping
public List<Student> getAllStudents() {
return studentService.getAllStudents();
}
@GetMapping("/{id}")
public Student getStudentById(@PathVariable int id) {
return studentService.getStudentById(id);
}
@PostMapping
public void createStudent(@RequestBody Student student) {
studentService.createStudent(student);
}
@PutMapping("/{id}")
public void updateStudent(@PathVariable int id, @RequestBody Student student) {
student.setId(id);
studentService.updateStudent(student);
}
@DeleteMapping("/{id}")
public void deleteStudent(@PathVariable int id) {
studentService.deleteStudent(id);
}
}
6. 데이터베이스 설정
- application.properties
Properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create
spring.h2.console.enabled=true
7. MyBatis 설정
- application.properties
Properties
mybatis.configuration.map-underscore-to-camel-case=true
8. 실행
- STS에서 프로젝트를 실행합니다.
- http://localhost:8080/h2-console에 접속하여 H2 콘솔을 확인합니다.
- Postman 또는 브라우저를 이용하여 API를 테스트합니다.
예제 실행 및 API 호출 방법
- 학생 목록 조회: GET /students
- 학생 상세 조회: GET /students/{id}
- 학생 추가: POST /students (Request Body에 학생 정보 JSON 형식으로 전달)
- 학생 수정: PUT /students/{id} (Request Body에 수정할 학생 정보 JSON 형식으로 전달)
- 학생 삭제: DELETE /students/{id}
H2 데이터베이스 생성 및 데이터 입력 방법
1. H2 데이터베이스 설정 확인
- application.properties 파일에 다음 설정이 추가되어 있는지 확인합니다.
Properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create
spring.h2.console.enabled=true
- spring.datasource.url은 H2 데이터베이스의 URL을 설정합니다. jdbc:h2:mem:testdb는 메모리 기반 데이터베이스를 사용하며, 애플리케이션이 종료되면 데이터가 사라집니다. 파일 기반 데이터베이스를 사용하려면 jdbc:h2:file:./testdb와 같이 설정할 수 있습니다.
- spring.jpa.hibernate.ddl-auto=create는 JPA가 자동으로 데이터베이스 스키마를 생성하도록 설정합니다.
- spring.h2.console.enabled=true는 H2 콘솔을 활성화합니다.
2. 애플리케이션 실행
- STS에서 프로젝트를 실행합니다.
3. H2 콘솔 접속
- 웹 브라우저를 열고 http://localhost:8080/h2-console에 접속합니다.
- JDBC URL, 사용자 이름, 비밀번호를 입력하고 "Connect" 버튼을 클릭합니다. (기본 설정인 경우 JDBC URL은 jdbc:h2:mem:testdb, 사용자 이름은 sa, 비밀번호는 비어있는 상태로 접속 가능합니다.)
4. 테이블 생성
- H2 콘솔에서 SQL 쿼리를 실행하여 테이블을 생성합니다. 예를 들어, 학생 정보를 저장하는 student 테이블을 생성하려면 다음 쿼리를 실행합니다.
SQL
CREATE TABLE student (
id INT PRIMARY KEY,
name VARCHAR(255),
phone VARCHAR(20)
);
5. 데이터 입력
- H2 콘솔에서 SQL 쿼리를 실행하여 데이터를 입력합니다. 예를 들어, 세 명의 학생 정보를 입력하려면 다음 쿼리를 실행합니다.
SQL
INSERT INTO student (id, name, phone) VALUES
(1, '홍길동', '010-1234-5678'),
(2, '김철수', '010-9876-5432'),
(3, '박영희', '010-1111-2222');
6. 데이터 확인
- H2 콘솔에서 SQL 쿼리를 실행하여 데이터를 확인합니다. 예를 들어, student 테이블의 모든 데이터를 조회하려면 다음 쿼리를 실행합니다.
SQL
SELECT * FROM student;
주의 사항
- H2 데이터베이스는 개발 및 테스트 환경에서 주로 사용됩니다. 운영 환경에서는 다른 데이터베이스를 사용하는 것이 좋습니다.
- 메모리 기반 데이터베이스를 사용하는 경우, 애플리케이션이 종료되면 데이터가 사라지므로 주의해야 합니다.
위 단계를 따르면 H2 데이터베이스를 생성하고 데이터를 입력할 수 있습니다.
StudentMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.student.mapper.StudentMapper">
<select id="selectAllStudents" resultType="com.example.student.vo.Student">
SELECT id, name, phone FROM student
</select>
<select id="selectStudentById" parameterType="int" resultType="com.example.student.vo.Student">
SELECT id, name, phone FROM student WHERE id = #{id}
</select>
<insert id="insertStudent" parameterType="com.example.student.vo.Student">
INSERT INTO student (id, name, phone) VALUES (#{id}, #{name}, #{phone})
</insert>
<update id="updateStudent" parameterType="com.example.student.vo.Student">
UPDATE student SET name = #{name}, phone = #{phone} WHERE id = #{id}
</update>
<delete id="deleteStudent" parameterType="int">
DELETE FROM student WHERE id = #{id}
</delete>
</mapper>
설명:
- <mapper namespace="com.example.student.mapper.StudentMapper">: namespace 속성은 Mapper 인터페이스의 패키지 경로와 클래스 이름을 지정합니다. 중요합니다.
- <select id="selectAllStudents" resultType="com.example.student.vo.Student">:
- id: Mapper 인터페이스의 메서드 이름과 일치해야 합니다.
- resultType: 쿼리 결과로 반환될 객체의 타입입니다. com.example.student.vo.Student는 VO 클래스의 전체 경로를 나타냅니다.
- SELECT id, name, phone FROM student: 실행할 SQL 쿼리입니다.
- <select id="selectStudentById" parameterType="int" resultType="com.example.student.vo.Student">:
- parameterType: 쿼리 실행 시 전달될 파라미터의 타입입니다. int는 정수형 파라미터를 의미합니다.
- WHERE id = #{id}: #{id}는 파라미터 값을 SQL 쿼리에 바인딩합니다.
- <insert id="insertStudent" parameterType="com.example.student.vo.Student">:
- parameterType: 삽입할 데이터를 담고 있는 객체의 타입입니다.
- <update id="updateStudent" parameterType="com.example.student.vo.Student">:
- parameterType: 수정할 데이터를 담고 있는 객체의 타입입니다.
- <delete id="deleteStudent" parameterType="int">:
- parameterType: 삭제할 데이터의 ID 타입을 나타냅니다.
중요 사항:
- 파일 위치: 위 XML 파일은 src/main/resources/mappers 폴더에 저장해야 합니다. application.properties 또는 application.yml 파일에 mybatis.mapper-locations=classpath:mappers/*.xml 설정을 추가하여 MyBatis가 Mapper XML 파일을 찾을 수 있도록 해야 합니다.
- 이름 규칙: Mapper XML 파일 이름은 Mapper 인터페이스 이름과 동일해야 합니다. (예: StudentMapper.xml)
- 오류 방지: 오타나 잘못된 SQL 구문이 없는지 꼼꼼히 확인하세요.
사용 방법:
- 위 XML 코드를 src/main/resources/mappers/StudentMapper.xml 파일에 저장합니다.
- application.properties 또는 application.yml 파일에 MyBatis 설정 (mybatis.mapper-locations)이 올바르게 되어 있는지 확인합니다.
- 프로젝트를 다시 빌드하고 실행합니다.
이제 StudentMapper 인터페이스를 통해 데이터베이스 작업을 수행할 수 있습니다. 예를 들어, studentMapper.selectAllStudents()를 호출하면 student 테이블의 모든 데이터를 조회하여 List<Student> 객체로 반환합니다.
'Spring( Framework )' 카테고리의 다른 글
WebSquare + Spring 연동 (3) | 2025.07.02 |
---|---|
Spring MVC Controller, Service, Mapper (MyBatis) 예제 (2) | 2025.02.06 |
ObjectMapper 매퍼 = new ObjectMapper() (0) | 2025.01.24 |
패키지에 impl을 붙이는 이유 (1) | 2025.01.24 |
REST 방식에서 쿼리스트링 Query string in REST method (1) | 2025.01.23 |