본문 바로가기

IT 공통

spring db 연결

Spring 애플리케이션에서 데이터베이스(DB) 연결을 설정하는 방법은 사용하는 기술 스택(Spring Boot, Spring JDBC, JPA, MyBatis 등)에 따라 다릅니다. 일반적으로 다음 단계로 진행합니다.


1. 의존성 추가 (Maven/Gradle)

Spring Boot를 사용할 경우, spring-boot-starter-data-jpa 또는 spring-boot-starter-jdbc를 추가합니다.

Maven (pom.xml)

<dependencies>
    <!-- Spring Boot JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
    <!-- H2 Database (테스트용) -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>

    <!-- MySQL Driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Gradle (build.gradle)

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    runtimeOnly 'com.h2database:h2' // H2 Database (테스트용)
    runtimeOnly 'mysql:mysql-connector-java' // MySQL Driver
}

2. application.properties / application.yml 설정

Spring Boot에서 데이터베이스 연결 정보를 설정합니다.

H2 (In-Memory DB)

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

MySQL

spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA 설정 (선택사항)
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

ddl-auto=update: 애플리케이션 실행 시 테이블 자동 생성/업데이트
ddl-auto=none: 기존 데이터베이스를 유지


3. Entity 및 Repository 생성 (JPA 사용 시)

Entity 클래스

import jakarta.persistence.*;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;

    // Getters and Setters
}

Repository 인터페이스

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

public interface UserRepository extends JpaRepository<User, Long> {
}

4. Service 및 Controller 구현

Service 클래스

import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
}

Controller 클래스

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public List<User> getUsers() {
        return userService.getAllUsers();
    }
}

5. 애플리케이션 실행 및 확인

  • Spring Boot 애플리케이션을 실행한 후,
    http://localhost:8080/users 에 접속하면 JSON 형식의 사용자 목록을 확인할 수 있습니다.

 

'IT 공통' 카테고리의 다른 글

Maria DB 설치  (1) 2025.02.05
Linux Spring 설정  (0) 2025.02.03
Java Spring의 장점과 단점  (1) 2025.02.02
웹 프로그래밍 언어  (0) 2025.02.01
apache php 연동  (0) 2025.01.31