JPA 설정 방법, Guide To JPA with Springboot
이전 포스팅에서 JPA를 왜 사용해야 하는지에 대해서 포스팅 했었습니다.
Link : aljjabaegi.tistory.com/553
이제, Springboot Framework에 JPA를 설정하는 방법을 알아보도록 하겠습니다.
[Spec]
Springboot 2.3.2
JPA 2.3.2
MariaDB
Springboot Project 생성 방법은 아래의 Link를 참고하세요.
Link : aljjabaegi.tistory.com/480
gradle project 기반으로 설명을 드리겠습니다.
Maven을 사용중이라면 pom.xml에 추가하시면 됩니다.
build.gradle 파일을 열어 dependencies 에 JPA, Mariadb-client를 추가해줍니다.
/*JPA*/
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.3.2.RELEASE'
/*mariadb-java-client*/
compile group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '2.6.1'
이제 프로젝트 폴더에서 gralde > refresh gradle project를 진행해 주시면 의존성이 주입됩니다.
이제 JPA에 대한 설정 클래스를 생성합니다.
group pakage > config pakage 내에 PersistanceJPAConfig Class를 생성합니다.
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.context.annotation.PropertySource;
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class PersistanceJPAConfig {
}
DB 관련 설정을 읽어오기 위해 PropertySource를 src/main/resources/application.properties로 설정했습니다.
[참고) application.properties]
spring.datasource.driverClassName=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://127.0.0.1:3306/JPA_TEST
spring.datasource.username=jpaTest
spring.datasource.password=jpaTest
Value를 사용해 application.properties 파일의 값을 매핑해 줍니다.
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.context.annotation.PropertySource;
import org.springframework.beans.factory.annotation.Value;
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class PersistanceJPAConfig {
@Value("${spring.datasource.driverClassName}")
private String driverClassName;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String userName;
@Value("${spring.datasource.password}")
private String password;
}
이제 설정정보를 활용해 DataSource를 Bean에 등록합니다.
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.context.annotation.PropertySource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class PersistanceJPAConfig {
@Value("${spring.datasource.driverClassName}")
private String driverClassName;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String userName;
@Value("${spring.datasource.password}")
private String password;
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(userName);
dataSource.setPassword(password);
return dataSource;
}
}
설정한 Datasource 설정을 활용해 Entity Manager 와 Transaction, Hibernate 설정 Bean을 추가해줍니다.
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.context.annotation.PropertySource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class PersistanceJPAConfig {
@Value("${spring.datasource.driverClassName}")
private String driverClassName;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String userName;
@Value("${spring.datasource.password}")
private String password;
@Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(userName);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] {"엔티티 패키지 경로"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
}
Database가 Oracle일 경우 application.properties의 DriverClassName, url 과
additionalProperties 메소드의 hibernate 방언(dialect)만 수정해 주시면 됩니다.
[Major DB Dialect]
Oracle(any) : org.hibernate.dialect.OracleDialect
Oracle10g : org.hibernate.dialect.Oracle10gDialect
MySql, MariaDB : org.hibernate.dialect.MySQL5Dialect
MsSql2000 : org.hibernate.dialect.SQLServerDialect
MsSql2005 : org.hibernate.dialect.SQLServer2005Dialect
MsSql2008 : org.hibernate.dialect.SQLServer2008Dialect
[hbm2ddl.auto options]
update : 객체와 스키마 비교, 기존 스키마 유지, 추가/삭제만 진행
create : 시작 시 스키마 삭제, 새로 생성
create-drop : SessionFactory 종료 시 스키마 삭제
JPA 관련 설정은 마무리 되었습니다.
다음 포스팅에서 Entity를 생성해 데이터를 조회하는 방법을 알아보도록 하겠습니다.
엔티티 매핑 방법
Link : aljjabaegi.tistory.com/562
'Programing > JPA' 카테고리의 다른 글
JPA with Springboot, 저장, 수정, 삭제 방법, RUD (1) | 2021.05.07 |
---|---|
JPA with Springboot, 조건 조회, Specification, Predicate, CriteriaBuilder (2) | 2021.05.04 |
JPA with Springboot, paging, sorting 방법 Pageable, Sort (0) | 2021.05.04 |
JPA with Springboot, Entity mapping 데이터 조회 방법 (4) | 2021.05.04 |
JPA (Java Persistance API) 란? 왜 써야하는가? (0) | 2021.03.24 |
댓글