isco
isco

Reputation: 360

DataSource in an OSGI container

I have a simple Spring App that connects to a DB via an EntityManager

So I have to following configuration:

<bean id="domainEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="TheManager" />
    <property name="dataSource" ref="domainDataSource" />
    <property name="packagesToScan" value="com.conztanz.persistence.stock.model" />

    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
        </props>
    </property>
</bean>


<bean id="domainDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url" value="jdbc:postgresql://localhost:5433/dbName" />
    <property name="username" value="xxxx" />
    <property name="password" value="xxxx" />
</bean>

This works fine when lunched via a main class (loading the AppContext manually)

But, once deployed into ServiceMix I get the following error :

Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [org.postgresql.Driver]

Upvotes: 1

Views: 1067

Answers (1)

Christian Schneider
Christian Schneider

Reputation: 19606

DriverManager does not work well in OSGi. The easiest way is to use a DataSource directly. Most DB drivers have such a class. If you instantiate it in your app context then it will work. The downside is though that it binds your application to the DB driver as it then will import the packages for the DataSource impl.

A more loosely coupled way is to use ops4j pax jdbc. It allows to create a DataSource as an OSGi service from a config in config admin. So in your app context you just have to add a dependency to a DataSource service. So your application is not bound to the specific DB driver. One typical use case is to use H2 in tests and oracle in production.

Upvotes: 3

Related Questions