I'm trying to write a generator for an angular-based CRUD application (scaffolding, but client-side, using angular)
Part of it consists on extracting the meta-information from GORM Now, I've hit a hard wall, apparently.
I want to handle the case where the ID field is not generated, but managed by the application. Say I have a class definition like:
@Resource(readOnly = false, formats = ['json', 'xml'])
class Phone {
int age
String phoneId
String imageUrl
String name
String snippet
static mapping = {
id name: 'phoneId', generator: 'assigned'
}
static constraints = {
snippet(nullable: true, maxSize: 2000)
}
}
I would like to retrieve the field serving as identifier for this class, which here should be 'phoneId'.
But if I ask for:
grailsApplication.getDomainClass(com.phonecat.Phone.getName()).identifier
What I get instead is a Property, called 'id' of type Long:
DefaultGrailsDomainClassProperty@6e59cb9b name = 'id', type = Long, persistent = true, optional = false, association = false, bidirectional = false, association-type = [null]]
Am I mis-using the getIdentifier method? Is there something I missed? Or have I hit a bug in Grails/GORM?
For completeness, here is the version of GORM I'm using (as far as I can tell... so many things changed recently on gorm side...):
from build.groovy:
compile "org.grails.plugins:hibernate5"
compile "org.hibernate:hibernate-core:5.1.2.Final"
compile "org.hibernate:hibernate-ehcache:5.1.2.Final"
Also, I'm using grails console plugin to run these tests:
runtime 'org.grails.plugins:grails-console:2.0.6'
(which I find really great) But probably the same could be run from within the normal command-line console.
Here is the code I used:
import com.phonecat.*
println grailsApplication.getDomainClass(Phone.getName()).identifier
def d = grailsApplication.getDomainClass(Phone.getName())
println "${d.class} ${d.clazz.name} ${d.identifier}"
def pd = Phone.findAll().each {c ->
println "${c.id} ${c.phoneId}"
}
null
The question is: supposing (as it actually happens to be ...) that I'm writing a plugin to retrieve the meta-information about a domain class; How can I obtain from GORM the information that this class has been assigned the field 'phoneId' as unique identifier, and this is the value I should look at when querying the resource through REST?
Generally you should favour the GORM API instead of the GrailsDomainClass if you want to inspect the mapping of you model. To do that you need to get a reference to the MappingContext (it can be dependency injected by Spring). Then: