Shashank
Shashank

Reputation: 524

How to get all the persistent properties of a grails Domain Class along with their constraints in a single Collection?

I need to get all the information about a particular Grails domain class, i.e. the persistent properties and the constraints related to them in a single collection. How do I do that?

Upvotes: 6

Views: 3194

Answers (5)

Vahe92
Vahe92

Reputation: 51

For Grails 4

List<PersistentProperty> props = Holders
                .grailsApplication
                .mappingContext
                .getPersistentEntity(object.class.name)
                .persistentProperties

Upvotes: 1

Al-Punk
Al-Punk

Reputation: 3660

Grails 4.x

def persistentEntity = grailsApplication.mappingContext.getPersistentEntity(object.getClass().getName())

Upvotes: 2

gargii
gargii

Reputation: 1130

I use this solution on Grails 3.3.9:

1) autowire this propoerty

MappingContext grailsDomainClassMappingContext

2) retrieve propertyList and constrainedProperties

ConstrainedDiscovery constrainedDiscovery = GrailsFactoriesLoader.loadFactory(ConstrainedDiscovery.class);
PersistentEntity crlPe = grailsDomainClassMappingContext.getPersistentEntity(MyDomain.name)

def propertyList = persistentEntity.getPersistentProperties()
Map constrainedProperties = constrainedDiscovery.findConstrainedProperties(crlPe);

Furthermore the documentation states you should be able to retrieve constraints by calling this:

MyDomain.constrainedProperties

It indeed works but with an annoying warning in the log. This solution may be easily used with the log message suppressed by:

logger("org.grails.core.DefaultGrailsDomainClass", ERROR)

Upvotes: 2

Trebla
Trebla

Reputation: 1172

As of grails 3.3, the accepted answer is no longer correct. DefaultGrailsDomainClass is now deprecated and the single argument constructor will throw an Exception that mappingContext is not yet initialized.

Inject the grailsDomainClassMappingContext bean and get the PersistentEntity with

def persistentEntity = grailsDomainClassMappingContext.getPersistentEntity(MyDomain.class.name)
def propertyList = persistentEntity.getPersistentProperties()

Upvotes: 8

Mike W
Mike W

Reputation: 3932

The following with get you a map with the property name as key and a map of constraints as values, works in Grails 3:

def d = new DefaultGrailsDomainClass(MyDomain.class)

def pp = d.persistentProperties.collectEntries {
    [it.name, d.constrainedProperties[it.name]?.appliedConstraints ]
}

Upvotes: 2

Related Questions