-
Create a data source and export it as a JNDI service.
Java:
@Component(service=javax.sql.DataSource.class, property="osgi.jndi.service.name=jdbc/myDataSource") public class MyDataSource extends SomeDbVendorDataSourceImpl implements javax.sql.DataSource { // ... }
or Blueprint:
<bean id="myDataSource" class="com.example.SomeDbVendorDataSourceImpl"> <!-- Inject the data source's dependencies (e.g. connection string). --> </bean> <service ref="myDataSource" interface="javax.sql.DataSource"> <service-properties> <entry key="osgi.jndi.service.name" value="jdbc/myDataSource"/> </service-properties> </service>
2. Create a META-INF/persistence.xml file. Provide the JNDI data source name.
```xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
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_2_0.xsd">
<persistence-unit name="com.example.app.jpa" transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<non-jta-data-source>osgi:service/jdbc/myDataSource</non-jta-data-source>
<!-- JPA configuration ... -->
</persistence-unit>
</persistence>
```
3. Add this to META-INF/Manifest.MF:
```
Meta-Persistence: META-INF/persistence.xml
JPA-PersistenceUnits: com.example.app.jpa
Import-Package: org.apache.openjpa.enhance;version="[2,3)",
org.apache.openjpa.persistence;version="[2,3)";resolution:=optional,
org.apache.openjpa.util;version="[2,3)";resolution:=optional
```
4. Inject the EntityManagerFactory where required.
```java
@Reference(target="(osgi.unit.name=com.example.app.jpa)")
public void setEntityManagerFactory(EntityManagerFactory emf) {
this.emf = emf;
}
```
I published this for a colleague who wanted to know how persistence units were being created and configured, not necessarily for the general public. Some things are missing such as the build configuration and I'm not going to go into further detail. If you find this useful as is, great!