Last active
August 29, 2015 14:04
-
-
Save deigote/d61e85e2c8c49f21db6a to your computer and use it in GitHub Desktop.
Grails - Hibernate-safe domain class property editor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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