DATA JPA Config

최종윤·2023년 1월 6일

JPA

목록 보기
7/15

https://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-one-configuration/

영속성 계층 설정하기
configuration class를 생성할 수 있다. 다음 단계를 따른다.
1. 앱 컨텍스트 설정 클래스에 쓰이는 properties 파일을 생성한다.
2. datasource 빈을 설정한다.
3. entity manager factory 빈을 설정한다.
4. transaction manager 빈을 설정한다.
5. annotation-driven transaction 관리를 가능하게 한다.
6. Spring Data JPA 설정하기

1 properties file 생성

properties file에 앱의 설정을 포함시킨다. 다음과 같은 단계로 생성한다.
1. db connection을 설정한다. JDBC driver class의 name, JDBC url, db user의 username과 password를 설정해야한다.
2. Hibernate를 다음과 같은 단계로 설정한다.
1. db dialect를 설정
2. app이 시작할때 db를 생성하고 app이 종료될때 db를 drop(삭제)하도록 Hibernate를 설정한다.
3. 새로운 db objects와 schema elements를 Hibernate가 생성할때 사용되는 naming 전략을 설정한다.
4. 호출된 SQL문을 console에 출력할지 말지 설정한다.
5. Hibernate가 console에 SQL문을 출력할때 형식에 맞춰서 보여주게 설정한다.

application.properties 코드

#Database Configuration
db.driver=org.h2.Driver
db.url=jdbc:h2:mem:datajpa
db.username=sa
db.password=

#Hibernate Configuration
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.hbm2ddl.auto=create-drop
hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
hibernate.show_sql=false
hibernate.format_sql=true

2. Datasource Bean 설정

다음 단계로 datasource bean을 설정한다.
1. app context가 종료될때 datasource 객체의 close()가 호출되도록 한다.
2. db connection을 설정한다 JDBC driver, url, username, password
3. HikariDataSource 객체를 생성하고 반환한다.


class PersistenceContext {
    @Bean(destroyMethod = "close")
    DataSource dataSource(Environment env) {
        HikariConfig dataSourceConfig = new HikariConfig();
        dataSourceConfig.setDriverClassName(env.getRequiredProperty("db.driver"));
        dataSourceConfig.setJdbcUrl(env.getRequiredProperty("db.url"));
        dataSourceConfig.setUsername(env.getRequiredProperty("db.username"));
        dataSourceConfig.setPassword(env.getRequiredProperty("db.password"));
 
        return new HikariDataSource(dataSourceConfig);
    }

}

3. EntityManagerFactory Bean 설정

다음 단계로 EMF를 설정할 수 있다.
1. LocalContainerEntityManagerFactoryBean 객체를 생성하여 JPA EntityManagerFactory를 생성한다.
2. 사용되는 datasource를 설정한다.
3. JpaVendorAdapter interface의 구현체 Hibernate를 설정한다.
Hibernate와 호환가능한 기본 값으로 설정한다.
4. entity classes를 검사하는 packages를 설정한다.
5. JPA provider에 사용되는 추가 설정을 제공하는데 쓰이는 JPA properties를 설정한다.

EntityManagerFactory Bean을 설정하는 method는 다음과 같다.

@Configuration
class PersistenceContext {

@Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, 
                                                            Environment env) {
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    entityManagerFactoryBean.setDataSource(dataSource);
    entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    entityManagerFactoryBean.setPackagesToScan("net.petrikainulainen.springdata.jpa.todo");

    Properties jpaProperties = new Properties();
 
    //Configures the used database dialect. This allows Hibernate to create SQL
    //that is optimized for the used database.
    jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));

    //Specifies the action that is invoked to the database when the Hibernate
    //SessionFactory is created or closed.
    jpaProperties.put("hibernate.hbm2ddl.auto", 
            env.getRequiredProperty("hibernate.hbm2ddl.auto")
    );

    //Configures the naming strategy that is used when Hibernate creates
    //new database objects and schema elements
    jpaProperties.put("hibernate.ejb.naming_strategy", 
            env.getRequiredProperty("hibernate.ejb.naming_strategy")
    );

    //If the value of this property is true, Hibernate writes all SQL
    //statements to the console.
    jpaProperties.put("hibernate.show_sql", 
            env.getRequiredProperty("hibernate.show_sql")
    );

    //If the value of this property is true, Hibernate will format the SQL
    //that is written to the console.
    jpaProperties.put("hibernate.format_sql", 
            env.getRequiredProperty("hibernate.format_sql")
    );

    entityManagerFactoryBean.setJpaProperties(jpaProperties);

    return entityManagerFactoryBean;
}
 
//Add the other beans here
}

4 TransactionManager Bean 설정

JPA provider와 Spring transaction 메커니즘을 통합하는 TransactionManager Bean을 생성해야한다.

Create a new JpaTransactionManager object.
Configure the entity manager factory whose transactions are managed by the created JpaTransactionManager object.
The method that configures the transaction manager bean looks as follows:

@Configuration
class PersistenceContext {

@Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(entityManagerFactory);
    return transactionManager;
}
 
//Add the other beans here
}

5 Enabling Annotation-Driven Transaction Management

We can enable annotation-driven transaction management by annotating the PersistenceContext class with the @EnableTransactionManagement annotation. The relevant part of the PersistenceContext class looks as follows:

@Configuration
@EnableTransactionManagement
class PersistenceContext {
 
//The beans are configured here
}

6 Configuring Spring Data JPA

We can configure Spring Data JPA by following these steps:

Enable Spring Data JPA by annotating the PersistenceContext class with the @EnableJpaRepositories annotation.
Configure the base packages that are scanned when Spring Data JPA creates implementations for our repository interfaces.
The relevant part of the PersistenceContext class looks as follows:

@Configuration
@EnableJpaRepositories(basePackages = {
        "net.petrikainulainen.springdata.jpa.todo"
})
@EnableTransactionManagement
class PersistenceContext {
 
//The beans are configured here
}    
profile
https://github.com/jyzayu

0개의 댓글