inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

자바 ORM 표준 JPA 프로그래밍 - 기본편

설정 파일 관리 방법 질문(spring X)

590

초알파

작성한 질문수 1

0

기존 프로젝트(spring X)에 jpa를 적용하는 중인데, persistence.xml 파일로 설정 후

Persistence.createEntityManagerFactory("test");

호출 시 아래의 예외가 발생하는 이슈가 있습니다.

java.lang.NoSuchMethodError: org.apache.xerces.impl.xs.XMLSchemaLoader.loadGrammar([Lorg/apache/xerces/xni/parser/XMLInputSource;)V

jpa_exception.pngxml 파싱 중 프로젝트에서 사용중인 xerces...jar 파일과 jdk의 rt.jar가 충돌되어 메서드를 찾지 못하는 현상으로 파악중입니다. (일반적인 jpa 예제에서는 rt.jar를 참조해야하지만, 해당 코드에서는 xerces...jar를 참조함)

해당 라이브러리를 걷어내기엔 기존 코드의 dependency가 염려되어 다른 파일(yml/properties)로 설정을 관리할 수는 없을까 싶은데, 검색 결과는 대부분 spring jpa 관련 내용이었습니다.

jpa 설정 시 xml 파일이 아닌, yml 또는 properties 파일로 관리하는 방법이 있는지 궁금합니다.

 

java jpa

답변 2

0

김영한

안녕하세요. 초알파님

이 부분은 저도 잘 모르겠습니다.

혹시 아시는 분 있으면 답변 부탁드려요.

감사합니다.

0

인프런 AI 인턴

안녕하세요, 인프런 AI 인턴이에요.

JPA 설정 파일을 xml 파일이 아닌 yml 또는 properties 파일로 관리하는 것은 가능합니다.

Spring에서는 application.yml 또는 application.properties 파일을 이용해 설정을 관리합니다. 이 파일은 src/main/resources 디렉토리 하위에 생성해야 합니다.

application.properties를 사용한다면, 다음과 같이 작성할 수 있습니다.

# 데이터베이스 설정
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=root
spring.datasource.password=password

# JPA 설정
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

# 엔티티 매니저 팩토리 생성
spring.jpa.open-in-view=false

아래는 application.yml을 사용한 예시입니다.

# 데이터베이스 설정
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost/test
    username: root
    password: password

# JPA 설정
spring:
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate.format_sql: true

# 엔티티 매니저 팩토리 생성
spring:
  jpa:
    open-in-view: false

이렇게 설정 파일을 작성한 후, EntityManagerFactory를 생성할 때는 아래와 같이 작성합니다.

@Configuration
@EnableTransactionManagement
public class JpaConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] { "com.example.demo" });

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());

        return em;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getProperty("spring.datasource.driver-class-name"));
        dataSource.setUrl(environment.getProperty("spring.datasource.url"));
        dataSource.setUsername(environment.getProperty("spring.datasource.username"));
        dataSource.setPassword(environment.getProperty("spring.datasource.password"));

        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);

        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", environment.getProperty("spring.jpa.hibernate.ddl-auto"));
        properties.setProperty("hibernate.show_sql", environment.getProperty("spring.jpa.show-sql"));
        properties.setProperty("hibernate.format_sql", environment.getProperty("spring.jpa.properties.hibernate.format_sql"));

        return properties;
    }

}

위와 같이 설정하면 xml 파일 대신 yml 또는 properties 파일로 JPA 설정을 관리할 수 있습니다.

다만, 현재 상황에서는 Xerces 라이브러리와 충돌하는 이슈가 발생하고 있으므로, 이를 해결해야 합니다. 해당 이슈는 다른 질문글에서도 언급되어 있으니, 이를 참고하시면 도움이 될 것입니다.

답변이 도움이 되었기를 바랍니다. 감사합니다.

0

초알파

친절한 설명 감사드립니다.

다만, Spring을 사용하지 않는 프로젝트에 JPA를 적용중이라, 설명해주신 방법을 어떻게 적용해야 할지 이해가 가지 않습니다.

커뮤니티에서 'Xerces', '충돌' 키워드로 검색해봤지만, 해당 라이브러리와의 충돌 이슈가 언급된 다른 질문글을 찾지 못하였습니다. 혹시 어느 글을 참고하면 좋을지 답변 주신다면 감사하겠습니다.

벌크연산에서 member.getAge 호출 시 영속성 컨텍스트에서 데이터를 가져오는건가요?

0

25

2

inheritance startegy 선택시 고려사항

0

22

1

Entity 동등성 비교

0

18

1

실무 조언 관련 질문입니다.

0

46

1

H2데이터베이스 파일 생성

0

56

2

서브쿼리 강의에서 ALL 예시 관련 질문드립니다.

0

52

2

수정또는 삭제시 영속성 엔티티에 값이 무조건 있어야 하나요?

0

52

1

JPQL 메소드와 락

0

55

1

Delivery @OneToOne

0

60

1

17강 4~5분대 테이블 값 조회가 안됩니다.

0

93

2

UnsupportedOperationException 발생

0

86

3

H2 Database 연결이 안됩니다.

0

92

2

연관관계 매핑 질문드립니다.

0

85

2

h2데이터베이스 실행오류

0

107

2

persistence.xml

0

106

2

양방향 연관관계에서 연관관계의 주인(mappedBy)을 왜 꼭 정해야 하나요?

0

80

1

영속성 컨텍스트

0

66

1

JPA 프록시

0

95

1

Native Query와 MyBatis

0

68

1

영속성 컨텍스트는 어떤 메모리에 저장되는건가요?

0

85

1

임베디드 타입 예시 코드 관련 질문

0

114

3

명시적 조인에서 별칭을 주면 왜 객체에 접근할 수 있나요

0

94

3

인텔리제이 패키지 커서 단축키 질문

0

108

2

혹시 현재는 ID 데이터 타입이 String이면 안되나요?

0

144

1