Spring 애플리케이션에서 데이터베이스(DB) 연결을 설정하는 방법은 사용하는 기술 스택(Spring Boot, Spring JDBC, JPA, MyBatis 등)에 따라 다릅니다. 일반적으로 다음 단계로 진행합니다.
Spring Boot를 사용할 경우, spring-boot-starter-data-jpa 또는 spring-boot-starter-jdbc를 추가합니다.
<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>
dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' runtimeOnly 'com.h2database:h2' // H2 Database (테스트용) runtimeOnly 'mysql:mysql-connector-java' // MySQL Driver }
Spring Boot에서 데이터베이스 연결 정보를 설정합니다.
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
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: 기존 데이터베이스를 유지
import jakarta.persistence.*; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // Getters and Setters }
import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { }
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(); } }
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(); } }