풀스택 백엔드 2026.06.19

syyu21b·2026년 6월 19일

풀스택 - 백엔드

목록 보기
33/49
post-thumbnail

[JPA에서 알아야 할 @OneToMany / @ManyToOne]

application.properties

# application.properties

# H2 Database 연결 설정
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# H2 Console 사용 설정 (웹 화면에서 DB 확인)
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

# JPA & Hibernate 설정
spring.jpa.database=H2
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

# DDL 자동 생성 옵션 (개발 환경)
spring.jpa.hibernate.ddl-auto=create-drop

# SQL 방언 설정
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

Post

package com.example.jpamanytoone.entity;

import jakarta.persistence.*;

import java.util.ArrayList;
import java.util.List;

@Entity
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // pk 자동 증가
    private Long id; // 게시글 번호

    @Column(nullable = false)
    private String title; // 게시글 제목

    @Column(nullable = false)
    private String content; // 게시글 내용

    @OneToMany(mappedBy = "post")
    private List<Comment> comments = new ArrayList<>();
}

Comment

package com.example.jpamanytoone.entity;

import jakarta.persistence.*;

@Entity
public class Comment {

    @Id
    private Long id; // 댓글 번호

    @Column(nullable = false)
    private String content; // 게시글 내용

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "post_id" , nullable = false)
    private Post post;
}

0개의 댓글