Grails: Delegating to GORM Persistence in Java
For a recent project, I needed to plug some Java code into a Grails app. I wanted to use GORM for persistence, but couldn't introduce the interfaces, proxies, and factories into the java code which is required for existing solutions to this problem.
Basically, my constraint was that the java code itself couldn't be altered to work inside the grails app. The solution I came up with is pretty simple, but works well.
The java code delegated to a DAO for persistence (using an interface). Here is what it looked like:
I packaged my groovy domain class to be org.smurf.Smurf so that the java code would be using the Grails generated class. Depending on the situation, this could involve a little bit of tweaking to the grails domain object to be compatible with any existing java classes. For this example, we're assuming an anemic bean so we don't need to do anything except declare the properties.
Next, I created an abstract DAO which delegates the sort of CRUD operations you see in a DAO to the GORM object.
After this, I simply needed to implement SmurfDao using this abstract class.
Using spring, we just need to make sure an instance of this class is injected into the SmurfingService. The following is an example using grails-app/conf/spring/resources.xml:
<?xml version="1.0" encoding="UTF-8"?>
<bean class="org.smurf.GormSmurfDao" autowire="constructor"/>
<bean id="smurfingService" class="org.smurf.SmurfingServiceImpl" autowire="constructor"/>