WEB/Back-end
(해커톤 연습, 준비) 스프링부트 시작하기
최새벽
2023. 6. 8. 17:30
2023년 6월 8일까지 현황
#01 build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '3.1.0'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'com.fts'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.mysql:mysql-connector-j'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
#02 controller - model - repository - service
: controller가 url으로부터 온 request에 따라 view를 사용자에게 보여주거나 service를 통하여 repository로 DB자원을 관리하거나, model의 내용을 활용할 수 있도록? 처리해주는 구조
(1) controller
ApiController
package com.fts.hackathon.controller;
import com.fts.hackathon.model.Student;
import com.fts.hackathon.service.StudentService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@RestController
public class ApiController {
private final StudentService studentService;
public ApiController(StudentService studentService) {
this.studentService = studentService;
}
@GetMapping("/get")
public List<String> get() {
return Arrays.asList("안녕", "이거받아");
}
@GetMapping("/getUser/{id}")
public Student getUser(@PathVariable("id") String id) {
return studentService.getUser(id);
}
}
UserController
package com.fts.hackathon.controller;
import com.fts.hackathon.model.Student;
import com.fts.hackathon.repository.StudentRepository;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class UserController {
private final StudentRepository studentRepository;
public UserController(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
@GetMapping("/")
public String index() {
return "index";
}
@PostMapping("/user/join")
public String join(Student student) {
Student student1 = new Student();
student1.setStudentName(student.getStudentName());
studentRepository.save(student1);
return "complete.html";
}
}
(2) model
Keyword
package com.fts.hackathon.model;
public enum Keyword {
NOASSIGNMENT, TEAMPLE
}
LearnedSubject
package com.fts.hackathon.model;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class LearnedSubject {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int learnedSubjectNum;
@ManyToOne
@JoinColumn(name = "student", nullable = false)
private Student student;
@Column(nullable = false, length = 500)
private String learnedSubjectName;
}
Professor
package com.fts.hackathon.model;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Professor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int professorNum;
@Column(nullable = false, length = 1000)
private String professorName;
@Column
private Keyword keyword1;
@Column
private Keyword keyword2;
@Column
private Keyword keyword3;
@OneToMany(mappedBy = "professor")
private List<Subject> subjectList;
}
Student
package com.fts.hackathon.model;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int studentNum;
@Column(nullable = false, length = 1000)
private String studentName;
@OneToMany(mappedBy = "student")
private List<LearnedSubject> learnedSubjectList;
}
Subject
package com.fts.hackathon.model;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Subject {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int subjectNum;
@Column(nullable = false)
private String subjectName;
@Column
private String subjectDepartment;
@Column(nullable = false)
private String subjectType;
@Column(nullable = false)
private int subjectCredit;
@Column
private String subjectTime;
@ManyToOne
@JoinColumn(name = "professor", nullable = false)
private Professor professor;
}
(3) repository
StudentRepository
package com.fts.hackathon.repository;
import com.fts.hackathon.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface StudentRepository extends JpaRepository<Student, Integer> {
Optional<Student> findByStudentName(String studentName);
}
(4) service
StudentService
package com.fts.hackathon.service;
import com.fts.hackathon.model.Student;
import com.fts.hackathon.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
public Student getUser(String studentName) {
return studentRepository.findByStudentName(studentName).orElseGet(()-> {
return null;
});
}
}
#03 application.yml
server:
port: 8081
servlet:
context-path:
encoding:
charset: UTF-8
enabled: true
force: true
spring:
mvc:
view:
prefix:
suffix: .html
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/hackertoon?serverTimezone=Asia/Seoul
username: minseo
password: 1234
jpa:
open-in-view: true
hibernate:
ddl-auto: create
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
use-new-id-generator-mappings: false
show-sql: true
properties:
hibernate.format_sql: true
jackson:
serialization:
fail-on-empty-beans: false
실행하면 MySQL에서 Table이랑 생김
(ddl-auto가 create이기 때문에 새로 시작하면 예전 내용 사라짐, 이전 남기고 싶으면 update로)
입력하여 제출하면 table에 내용 저장된다.