Spring Boot数据源

时间:2015-02-19 01:29:02

标签: spring spring-boot

我在我的应用程序中使用Spring启动并尝试使用UCP创建一个DataSource并遇到以下错误。类似的问题已经发布,但有兴趣知道这种配置的原因。

Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:205)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:852)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:845)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:844)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
... 143 more

但是我添加了hibernate.dialect。

Aplication.java,

@Configuration //@EnableAutoConfiguration @ComponentScan @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) @SpringBootApplication public class DialerApplication {

public static void main(String[] args) {
    SpringApplication.run(DialerApplication.class, args);
} }

DataSource文件,

@Configuration
@ComponentScan
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(entityManagerFactoryRef =     "dialerEntityManagerFactory", transactionManagerRef = "dialerTransactionManager", basePackages = { "com.nervytech.dialer.db.repository" })
public class ApplicationDataSource {

/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory
        .getLogger(ApplicationDataSource.class);

/** The Constant TEST_SQL. */
private static final String TEST_SQL = "select 1 from dual";

/** The pooled data source. */
private PoolDataSource pooledDataSource;

/** The environment. */
private Environment environment;

/** The Constant CONNECTION_WAIT_TIMEOUT_SECS. */
private static final int CONNECTION_WAIT_TIMEOUT_SECS = 300;

/**
 * Data source.
 * 
 * @return the pool data source
 */
@Bean(name = "dialerDataSource")
@Primary
public PoolDataSource dialerDataSource() {

    this.pooledDataSource = PoolDataSourceFactory.getPoolDataSource();
    final String databaseDriver = environment
            .getRequiredProperty("application.datasource.driverClassName");
    final String databaseUrl = environment
            .getRequiredProperty("application.datasource.url");
    final String databaseUsername = environment
            .getRequiredProperty("application.datasource.username");
    final String databasePassword = environment
            .getRequiredProperty("application.datasource.password");
    final String initialSize = environment
            .getRequiredProperty("application.datasource.initialSize");
    final String maxPoolSize = environment
            .getRequiredProperty("application.datasource.maxPoolSize");
    final String minPoolSize = environment
            .getRequiredProperty("application.datasource.minPoolSize");
    // final String poolName =
    // environment.getRequiredProperty("application.datasource.poolName");

    try {
        pooledDataSource.setConnectionFactoryClassName(databaseDriver);
        pooledDataSource.setURL(databaseUrl);
        pooledDataSource.setUser(databaseUsername);
        pooledDataSource.setPassword(databasePassword);
        pooledDataSource.setInitialPoolSize(Integer.parseInt(initialSize));
        pooledDataSource.setMaxPoolSize(Integer.parseInt(maxPoolSize));
        pooledDataSource.setMinPoolSize(Integer.parseInt(minPoolSize));
        pooledDataSource.setSQLForValidateConnection(TEST_SQL);
        pooledDataSource.setValidateConnectionOnBorrow(Boolean.TRUE);
        pooledDataSource
                .setConnectionWaitTimeout(CONNECTION_WAIT_TIMEOUT_SECS);
        // pooledDataSource.setConnectionPoolName(poolName);
    } catch (NumberFormatException e) {
        LOGGER.error("Unable to parse passed numeric value", e);
    } catch (SQLException e) {
        LOGGER.error("exception creating data pool", e);
    }

    LOGGER.info("Setting up datasource for user:{} and databaseUrl:{}",
            databaseUsername, databaseUrl);
    return this.pooledDataSource;
}

@Bean(name = "dialerEntityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    lef.setDataSource(dialerDataSource());
    lef.setJpaVendorAdapter(vendorAdapter);
    lef.setPackagesToScan("com.nervytech.dialer.db.domain");
    lef.setJpaProperties(additionalProperties());
    lef.setPersistenceUnitName("dialerPersistenceUnit");
    lef.afterPropertiesSet();
    return lef.getObject();
}

@Bean(name = "dialerTransactionManager")
public PlatformTransactionManager transactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(entityManagerFactory());
    return transactionManager;
}

Properties additionalProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.dialect",
            "org.hibernate.dialect.MySQL5Dialect");     
    properties.setProperty("hibernate.show_sql","true");

    return properties;
}

/**
 * Sets the environment.
 * 
 * @param environment
 *            the new environment
 */
@Autowired
public void setEnvironment(Environment environment) {

    this.environment = environment;
}

}

的pom.xml,

<?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.nervytech</groupId>
<artifactId>dialer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>dialer</name>
<description>Nervy Dialer</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.1.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>



<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <start-class>com.nervytech.dialer.DialerApplication</start-class>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-integration</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> 
        </dependency> -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-ws</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.integration</groupId>
        <artifactId>spring-integration-mail</artifactId>
        <version>4.0.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.4</version>
    </dependency>
    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
        <!-- <version>3.2.1</version>-->
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ucp</artifactId>
        <version>11.2.0.3</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <!-- <version>5.1.6</version>-->
    </dependency>
    <dependency>
        <groupId>javax.json</groupId>
        <artifactId>javax.json-api</artifactId>
        <version>1.0</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </pluginRepository>
    <pluginRepository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>
</pluginRepositories>

虽然dialerEntityManagerFactory中有方言,但不确定为什么会出现此错误。

谢谢, Baskar.S

1 个答案:

答案 0 :(得分:1)

经过进一步研究,我找到了一个解决方案并想分享。 下面是我的属性文件。

application.datasource.driverClassName=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
application.datasource.url=jdbc:mysql://localhost:3306/dbName 
application.datasource.username=root
application.datasource.password=root
application.datasource.initialSize=5
application.datasource.maxPoolSize=5
application.datasource.minPoolSize=5

datasource.url中的数据库名称后面有一些空格。如果在启动期间未建立数据库连接,Spring将抛出此类错误。

但是添加以下属性将允许您在未建立数据库连接的情况下启动Spring启动。

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

但是,只要在启动后建立数据库连接,Spring引导就会立即重新建立连接。

谢谢, Baskar.S