ChristianMittendorf: I've done some testing on HiveMind integration of Cayenne. My solution requires your webapp to use servlet specification 2.4 or newer (see WebApplicationContextProvider).

Put this listener entry into your application web.xml. This entry will put a DataContext into your session and bind it automatically to the request.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
	
	<display-name>...</display-name>
	[...]
	<listener>
	   <listener-class>org.objectstyle.cayenne.conf.WebApplicationContextProvider</listener-class>
	</listener>
	[...]
</web-app> 

Describe the new service in a hivemind.xml:

<?xml version="1.0" encoding="utf-8"?>
<module id="de.example.hivemind" version="0.0.1">

	<service-point id="dataContextService" interface="de.example.hivemind.DataContextService" />
	
	<implementation service-id="dataContextService">
	 	<invoke-factory>
			<construct class="de.example.hivemind.impl.DataContextServiceImpl" />
		</invoke-factory>
	</implementation>

</module>

Create the Interface for the new Service:

package de.example.hivemind;

import org.objectstyle.cayenne.access.DataContext;

public interface DataContextService
{
	public DataContext getDataContext();
}

and the write the implementation:

package de.example.hivemind.impl;

import org.objectstyle.cayenne.access.DataContext;

import de.example.hivemind.DataContextService;

public class DataContextServiceImpl implements DataContextService
{	
	public DataContext getDataContext()
	{
		return DataContext.getThreadDataContext();
	}
}

The following extension has not been tested, but it should make this service work in other applications than webapps:

package de.example.hivemind.impl;

import org.objectstyle.cayenne.access.DataContext;
import java.lang.IllegalStateException;
import de.example.hivemind.DataContextService;

public class DataContextServiceImpl implements DataContextService
{	
	public DataContext getDataContext()
	{
		DataContext dc = null;
		try {
			dc = DataContext.getThreadDataContext();
		} catch (IllegalStateException e) {}
		if(dc == null) {
			// Attention, this will not work in Web context if you 
			// forgot to include the WebAppContextProvider, because
			// the DataContext is not bound to the http session!
			dc = DataContext.createDataContext();
			DataContext.bindThreadDataContext(dc);
		}
		return dc;
	}
}
  • No labels