프로그래밍/Java

IntelliJ 이용하여 스프링 부트 + JPA + Mysql 간단한 예제

소행성왕자 2023. 8. 22. 13:30

JAVA 11 사용

build.gradle

plugins {
    id 'java'
    id 'war'
    id 'org.springframework.boot' version '2.7.14'
    id 'io.spring.dependency-management' version '1.1.2'
}

group = 'com.naya'
version = '0.0.1-SNAPSHOT'

java {
    sourceCompatibility = '11'
}

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.mysql:mysql-connector-j'
    runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
    annotationProcessor 'org.projectlombok:lombok'
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

resources/application.yml

server:
  address: localhost
  port: 8080

spring:
  jpa:
    show-sql: true
    database: mysql

  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localahost:3306/dbname?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Seoul
    username: username
    password: password

  thymeleaf:
    cache: false
    prefix: file:src/main/resources/templates/
    suffix: .html
  devtools:
    restart:
      enabled: true

DB table 스키마

CREATE TABLE bbs  (
  `idx` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `content` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `reg_date` datetime NULL DEFAULT NULL,
  `update_date` datetime NULL DEFAULT NULL,
  PRIMARY KEY (`idx`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

프로젝트 구조

UserController.java

package com.naya.shopjpa.controller;

import com.naya.shopjpa.model.Bbs;
import com.naya.shopjpa.model.BbsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private BbsRepository userRepository;

    @PostMapping("/user")
    public Bbs create(@RequestBody Bbs user) {
        return userRepository.save(user);
    }

    @GetMapping("/user/{id}")
    public String read(@PathVariable Long id) {

        Optional<Bbs> userOptional = userRepository.findById(id);
        userOptional.ifPresent(System.out::println);

        return "successfully executed";
    }
}

model/Bbs.java

package com.naya.shopjpa.model;

import lombok.Data;

import org.springframework.data.annotation.Id;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

@Entity
@Data
public class Bbs {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String title;
    private String content;
    private String name;
    private String reg_date;
    private String update_date;
    @javax.persistence.Id
    private Long idx;


}

model/BbsRepository.java

package com.naya.shopjpa.model;

import org.springframework.data.jpa.repository.JpaRepository;

public interface BbsRepository extends JpaRepository<Bbs, Long> {
}

테스트