如何使用JNDI链接(Wildfly)创建数据源



如何使用JTA连接到数据库,而无需持久,仅使用注释?以及如何使用JNDI链接创建数据源?

我有wildfly_10 java的jndi链接:jboss/dataSources/postgredatasource

persistence.xml代码

    `<persistence-unit name="Unit1" transaction-type="JTA"> 
        <jta-data-source>java:jboss/datasources/PostgreDataSource</jta-data-source> 
        <properties> 
            <property name="hibernate.hbm2ddl.auto" value="update"/> 
        </properties> 
    </persistence-unit>`

我的配置文件:

@Configuration
@EnableTransactionManagement
@ComponentScan({ "net.myProg" })
@PropertySource(value = { "classpath:application.properties" })
@EnableJpaRepositories("net.myProg.repository")
public class HibernateConfiguration {
    @Autowired
    private Environment environment;
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource());
        entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        entityManagerFactoryBean.setPackagesToScan("net.myProg.model");
        entityManagerFactoryBean.setJpaProperties(hibernateProperties());
        return entityManagerFactoryBean;
    }
    @Bean
    public JpaTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
        return transactionManager;
    }
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
//        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }
    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        //Lazy load initializayion. Hibernate сам открывает сессию для получения lazy объекта, если это нужно
        properties.put("hibernate.enable_lazy_load_no_trans", environment.getRequiredProperty("hibernate.enable_lazy_load_no_trans"));
//        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        return properties;
    }
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
        db.setDataSource(dataSource());
        return db;
    }
}

在此处找到答案如何使用Tomcat在春季提供的JNDI DataSource?

@configuration公共类MainConfig {

...
@Bean
DataSource dataSource() {
    DataSource dataSource = null;
    JndiTemplate jndi = new JndiTemplate();
    try {
        dataSource = jndi.lookup("java:comp/env/jdbc/yourname", DataSource.class);
    } catch (NamingException e) {
        logger.error("NamingException for java:comp/env/jdbc/yourname", e);
    }
    return dataSource;
}

}

使用JNDI名称创建用于数据源的BEAN

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springmodules.org/schema/ehcache
        http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-3.1.xsd">
    <bean id="appDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>java:jboss/datasources/xyzDataSouce</value>
        </property>
    </bean>
</beans>

如果您使用JPA存储库可以使用此数据源

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springmodules.org/schema/ehcache
        http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/data/jpa 
        http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-4.2.xsd">        
    <tx:annotation-driven transaction-manager="apptransactionManager" />
    <bean id="apptransactionManager"  class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="appEntityManagerFactory" />
    </bean>
    <bean id="appEntityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaVendorAdapter">
              <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="dataSource" ref="appDataSource" />
        <property name="packagesToScan">
            <list>
                <value>net.something.something</value>
            </list>
        </property>
        <property name="jpaPropertyMap">
            <props>
                <prop key="hibernate.show_sql">${jpaVendorAdapter.hibernate.show_sql}</prop>
                <prop key="hibernate.dialect">${jpaVendorAdapter.hibernate.dialect}</prop>
                <prop key="hibernate.jdbc.batch_size">${jpaVendorAdapter.hibernate.jdbc.batch_size}</prop>
                <prop key="hibernate.hbm2ddl.auto">${jpaVendorAdapter.hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.default_schema">${jpaVendorAdapter.hibernate.default_schema}</prop>
                <prop key="org.hibernate.envers.audit_table_suffix">${jpaVendorAdapter.org.hibernate.envers.audit_table_suffix}</prop>
                <prop key="org.hibernate.envers.audit_table_prefix">${jpaVendorAdapter.org.hibernate.envers.audit_table_prefix}</prop>
                <prop key="org.hibernate.envers.revision_field_name">${jpaVendorAdapter.org.hibernate.envers.revision_field_name}</prop>
                <prop key="org.hibernate.envers.revision_type_field_name">${jpaVendorAdapter.org.hibernate.envers.revision_type_field_name}</prop>
            </props>
        </property>
    </bean>
    <jpa:repositories base-package="net.something.something.core.dao" transaction-manager-ref="apptransactionManager"/>         
    <!-- Needed for @PersistenceContext annotation -->
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> 
    <tx:annotation-driven transaction-manager="apptransactionManager"/>
    <aop:aspectj-autoproxy/>
    <!-- JSR-303 bean validation -->
    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <!-- <property name="providerClass" value="org.apache.bval.jsr303.ApacheValidationProvider" /> -->
    </bean>
</beans>

如果您愿意,可以创建两个文件,并将两个文件添加到应用程序-Context XML中,一切都将开始工作

最新更新