programing

Postgre를 사용하여 데이터 소스를 생성할 때 예외 발생Spring Boot SQL 드라이버

javajsp 2023. 2. 23. 22:02

Postgre를 사용하여 데이터 소스를 생성할 때 예외 발생Spring Boot SQL 드라이버

MKyong의 예에 따라 Spring Boot을 사용하여 웹 이외의 응용 프로그램을 생성하려고 하는데 다음 오류가 발생했습니다.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.5.RELEASE)

(...) Several not relevant INFO log lines

2018-12-12 11:45:29.420 ERROR 30866 --- [ main] com.zaxxer.hikari.HikariConfig           : Failed to load driver class org.postgresql.Driver from HikariConfig class classloader sun.misc.Launcher$AppClassLoader@18b4aac2
2018-12-12 11:45:29.423  WARN 30866 --- [ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'ldConfiguration': Could not bind properties to 'LdConfiguration' : prefix=datasources.ld, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'datasources.ld' to es.ortoplus.LdConfiguration$$EnhancerBySpringCGLIB$$625f0f64
2018-12-12 11:45:29.435  INFO 30866 --- [ main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-12-12 11:45:29.440 ERROR 30866 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under 'datasources.ld' to es.oplus.LdConfiguration$$EnhancerBySpringCGLIB$$625f0f64:

    Property: datasources.ld.driverclassname
    Value: org.postgresql.Driver
    Origin: class path resource [application.yml]:3:22
    Reason: Failed to load driver class org.postgresql.Driver in either of HikariConfig class loader or Thread context classloader

Action:

Update your application's configuration

conf 파일(application.yml)은

datasources:
  ld:
    driverClassName: org.postgresql.Driver
    jdbc-url: jdbc:postgresql://localhost:5432/oplus
    username: user123
    password: 123456
    connection-test-query: SELECT 1

그리고 Maven pom.xml 파일에 다음과 같이 추가했습니다.

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <!--<version> (managed by Spring Boot)42.2.5 </version> -->
</dependency>

내 진입점 클래스:

@SpringBootApplication
public class App implements CommandLineRunner {

    @Autowired private UsuarioRepository usuarioRep;
    @Override
    public void run(String... args) throws Exception {
        App app = new App();
        System.out.printf("Users: %1d", app.usuarioRep.count());

    }

    public static void main(String[] args) throws ClassNotFoundException {
        //Class.forName("org.postgresql.Driver");
        SpringApplication.run(App.class, args);

    }

}

보시다시피, 저는 수업이 이미 수업 경로에 있는지 확인하려고 노력했습니다.이 행을 코멘트 해제하면 ClassNotFoundException이 나왔기 때문에 Maven이 종속성을 포함하지 않기 때문에 오류가 발생한 것 같습니다.범위를 다음과 같이 설정하려고 했습니다.runtime그래도 실패합니다.

어쨌든 설정 클래스는 다음과 같습니다.

@Configuration
@ConfigurationProperties(prefix = "datasources.ld")
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "postgreEntityManagerFactory", transactionManagerRef = "postgreTransactionManager",
        basePackages = "es.plus.l.dao")
public class LdConfiguration extends HikariConfig {

    @Bean(name = "postgreDataSource")
    @Primary
    public DataSource dataSource() {
        return new HikariDataSource(this);
    }

    @Bean(name = "postgreEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean postgreEntityManagerFactory(
            final EntityManagerFactoryBuilder builder,
            @Qualifier("postgreDataSource") final DataSource dataSource) {
        final LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setJpaVendorAdapter(this.vendorAdaptor());
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPersistenceUnitName("postgre");
        entityManagerFactoryBean.setPackagesToScan("es.oplus.ld.model");
        entityManagerFactoryBean.setJpaProperties(this.jpaHibernateProperties());
        entityManagerFactoryBean.afterPropertiesSet();
        return entityManagerFactoryBean;
    }

    @Bean(name = "postgreTransactionManager")
    @Primary
    public PlatformTransactionManager postgreTransactionManager(
          @Qualifier("postgreEntityManagerFactory") final EntityManagerFactory emf) {
        return new JpaTransactionManager(emf);
    }

    private HibernateJpaVendorAdapter vendorAdaptor() {
        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        // put all the adapter properties here, such as show sql
        return vendorAdapter;
    }

    private Properties jpaHibernateProperties() {
        final Properties properties = new Properties();
        // put all required jpa propeties here
        return properties;
    }

}

문제를 발견했습니다.Eclipse는 종속성을 제대로 보여주었지만 클래스가 실제로 존재하지 않는 것 같아서 수동으로 실행하려고 했습니다.그래서 실행했을 때:

mvn clean install

Maven으로부터 이 에러를 받았습니다.

error reading /home/pablo/.m2/repository/org/postgresql/postgresql/42.2.5/postgresql-42.2.5.jar; invalid LOC header (bad signature)

Maven이 손상된 버전의 항아리를 다운받아서 오류가 발생했군요.

삭제하여 강제로 새 다운로드를 실행하면 문제가 해결되었습니다.

다음 코드를 pom.xml에 추가합니다.

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>

JDBC 드라이버와 Postgre를 모두 가지고 있는지 확인합니다.pom.xml의 SQL 의존관계는 다음과 같습니다.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency> 

내 경우 종속성 아래에 pom.xml이 없습니다.다음 코드를 추가하면 정상적으로 동작합니다.

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>

IntelliJ Idea 를 사용하고 있는 경우는, IDE 를 재기동합니다.

언급URL : https://stackoverflow.com/questions/53741514/exception-when-creating-datasource-with-postgresql-driver-in-spring-boot