Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save deigote/d61e85e2c8c49f21db6a to your computer and use it in GitHub Desktop.
Save deigote/d61e85e2c8c49f21db6a to your computer and use it in GitHub Desktop.
Grails - Hibernate-safe domain class property editor
import static org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil.unwrapIfProxy
public class DomainClassLookupPropertyEditor extends PropertyEditorSupport {
Class domainClass
String property
Boolean doAssert = true
String getAsText() {
value."$property"
}
void setAsText(String text) {
def alreadyInSessionValue = searchValueInCurrentSession(text)
value = alreadyInSessionValue != null ?
domainClass.load(alreadyInSessionValue.id) : searchValueInNewSession(text)
assert doAssert && value, "no $domainClass found for $property '$text'"
}
private searchValueInNewSession(String text) {
domainClass.withNewSession {
domainClass."findBy${property.capitalize()}"(text)
}
}
private searchValueInCurrentSession(String text) {
domainClass.withSession { session ->
session.persistenceContext.entityEntries.find { instance, persistenceEntry ->
unwrapIfProxy(instance).getClass() == domainClass &&
instance[property].toString() == text
}?.key
}
}
static DomainClassLookupPropertyEditor newInstance(Class domainClass, String propToLookup) {
new DomainClassLookupPropertyEditor(domainClass: domainClass, property: propToLookup)
}
}
public class MyPropertyEditorRegistrar implements PropertyEditorRegistrar {
static Map<Class, String> domainClassByPropertyCustomBinders = [
(User): 'id', (Role): 'authority'
]
public void registerCustomEditors(PropertyEditorRegistry propertyEditorRegistry) {
domainClassByPropertyCustomBinders.each { domainClass, prop ->
registerDomainClassLookupPropEditor(propertyEditorRegistry, domainClass, prop)
}
}
private registerDomainClassLookupPropEditor(
PropertyEditorRegistry propertyEditorRegistry, Class domainClass, String propToLookup
) {
propertyEditorRegistry.registerCustomEditor(
domainClass, DomainClassLookupPropertyEditor.newInstance(domainClass, propToLookup)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment