Setting Up Spring Boot Project
Database μ κΈ°λ³Έμ μΈ μ€μ μ λ§μΉ μ΄νμ Spring Boot Project μ 본격μ μΌλ‘ λ€μ΄κ°λ³΄λλ‘ νμ.
Automatic Data Source Configuration
Hibernate λ Spring Boot μ JPA default implementation μ΄λΌλ μ μ μμμ μ΄ν΄λ³΄μλ€.
EntityManager λ Hibernate μ μΌλΆλΆμΌλ‘μ¨, query μ μμ± λ±μ λ΄λΉνλ main component μ΄λ€. EntityManager, DataSource λ€μ λͺ
μμ μΌλ‘ @Component λ±μ annotation μ΄ μ€μ λμ΄ μμ§ μμ§λ§, Spring Boot μ Auto-configuration μ λ°λΌμ μλμΌλ‘ Bean μ΄ μμ±λλ€.
μ΄νμ μ΄ Bean λ€μ Application μ DAO λ±μ injection νμ¬ μ¬μ©ν μ μλ€. DAO λ Database μ Application μ μνΈμμ©μ λ΄λΉνλ obejct μ΄λ€. λ μμΈν λ΄μ©μ λμ€μ μμ보μ.
Setting up Project with Spring Initializr
Spring Initializr μμ λ€μ λ κ°μ dependency λ₯Ό μΆκ°ν΄μΌ νλ€.
- MySQL Driver:
mysql-connector-j- Spring Data JPA:
spring-boot-starter-data-jpa
Spring Boot - Auto Configuration
Spring Boot λ Maven POM file μ κΈ°λ°μΌλ‘ automatic νκ² data source λ₯Ό μ€μ ν΄μ€ κ²μ΄λ€.
DB connection μ κ²½μ°, application.properties νμΌμ ν΅νμ¬ μ€μ ν μ μλ€. μλμ κ°μ΄ μμ±νλ©΄ λλ€.
spring.datasource.url=jdbc:mysql://localhost:3306/student_tracker
spring.datasource.username=springstudent
spring.datasource.password=springstudentspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver λ₯Ό ν΅νμ¬ JDBC driver class name μ μ§μ ν΄μ£Όμ§ μμλ Spring Boot κ° μμμ μλμΌλ‘ URL μ ν΅νμ¬ MySQL μμ νμ
νλ€.
Creating Spring Boot - Command Line App
μ°μ Hibernate / JPA μ μ§μ€νκΈ° μνμ¬ Application μ Command Line κΈ°λ°μΌλ‘ μμ±ν΄λ³΄μ. μ΄νμ CRUD REST API λ₯Ό μ¬μ©νμ¬ λ°μ μν¬ κ²μ΄λ€.
λ€μ μ½λλ₯Ό μ΄ν΄λ³΄μ.
@SpringBootApplication
public class CrudDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CrudDemoApplication.class, args)
}
@Bean
public CommandLineRunner commandLineRunner(String[] args) {
return runner -> {
System.out.println("Hello World");
};
}
}CommandLineRunner λ Application μ΄ μμλ μ΄νμ νΉμ μ½λλ₯Ό μ€νν μ μλλ‘ μ 곡λλ Interface μ΄λ€. μ΄λ₯Ό implement νλ©΄ Spring Boot Application μ ꡬλ μμ μ μνλ μμ
λ±μ μνν μ μλ€.
run() method λ Application μ΄ μμ ν μμλκΈ° μ μ μ€νλλ€. run() method μ μ§ν κ³Όμ μμ ApplicationContext κ° λ¨Όμ μ΄κΈ°νλκ³ , λͺ¨λ Bean λ€μ΄ μμ±λκ³ μ΄κΈ°νλ μ΄νμ CommandLineRunner μ μ½λλ€μ΄ μ€νλλ€.