Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: add ConfigurableDataSource description

...

Code Block
java
java
titleProducer for a @TransactionScoped entity manager
public class DataBaseProducer
{
    @PersistenceContext(unitName="default")
    private EntityManager entityManager;

    @Produces
    @TransactionScoped
    public EntityManager createEntityManager()
    {
        return this.entityManager;
    }

    public void dispose(@Disposes EntityManager entityManager)
    {
        if(entityManager.isOpen())
        {
            entityManager.close();
        }
    }
}

ConfigurableDataSource

Configuring the data connection properties in JPA projects in pure Java EE is always a painful task. Directly configuring the JDBC driver class and database credentials in the persistence.xml is a no-go.
Configuring a DataSource via JNDI sounds good at the first glance, but has serious flaws:

  • providing JNDI for native unit tests (without starting the EE container) requires a lot of tweaking.
  • JNDI locations for configured DataSources are not specified. Configuring the same myDb DataSource in n EE containers will give you n different JNDI locations - thus it's not possible to use a fixed JNDI location in your persistence.xml

A solution to this problem is provided via the Apache MyFaces CODI ConfigurableDataSource. This is a thin DataSource wrapper which will get it's configuration via CDI mechanics.

Code Block
XML
XML
titlepersistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

    <persistence-unit name="test" >
        <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>

        <class>org.apache.myfaces.extensions.cdi.jpa.test.TestEntity</class>

        <properties>
            <property name="openjpa.jdbc.DBDictionary" value="hsql" />
            <property name="openjpa.ConnectionDriverName"
             value="org.apache.myfaces.extensions.cdi.jpa.impl.datasource.ConfigurableDataSource"/>
            <property name="openjpa.ConnectionProperties" value="connectionId=core"/>
        </properties>
    </persistence-unit>
</persistence>

The configuration itself is provided by implementing the CODI DataSourceConfig class. The DataSourceConfig determines whether a JNDI path, a JDBC connection or another DataSource should get used, by just returning the proper values. You can use all the flexible CDI and CODI mechanisms like @ProjectStageActivated, @ExpressionActivated, @Alternative, @Specializes, etc and even if/then/else,... to find the perfect settings for your current runtime environment!