Reputation: 1
with gorm-hibernate5-spring-boot:8.1.0
<dependency>
<groupId>org.grails</groupId>
<artifactId>gorm-hibernate5-spring-boot</artifactId>
<version>8.1.0</version>
</dependency>
my code was:
def groovyCode = """
package com.example.gorm.entity
import grails.gorm.annotation.Entity
import org.grails.datastore.gorm.GormEntity
@Entity
class Person implements{
String firstName
String lastName
}
"""
def groovyClass2= loader.parseClass(groovyCode);
def person = groovyClass.getDeclaredConstructor().newInstance()
person.invokeMethod("find", { lastName == "John" })
Running the above code will throw an exception:
Either class [com.example.newgorm.entity.Person] is not a domain class or GORM has not been initialized correctly or has already been shutdown. Ensure GORM is loaded and configured correctly before calling any methods on a GORM entity.
I found that domain will be registered to STATIC_APIS in GormEnhancer.groovy at project startup. Can I dynamically register Person domain now?
/**
* Registers a new entity with the GORM enhancer
*
* @param entity The entity
*/
void registerEntity(PersistentEntity entity) {
Datastore datastore = this.datastore
if (appliesToDatastore(datastore, entity)) {
def cls = entity.javaClass
List<String> qualifiers = allQualifiers(this.datastore, entity)
if(!qualifiers.contains(ConnectionSource.DEFAULT)) {
def firstQualifier = qualifiers.first()
def staticApi = getStaticApi(cls, firstQualifier)
def name = entity.name
STATIC_APIS.get(ConnectionSource.DEFAULT).put(name, staticApi)
def instanceApi = getInstanceApi(cls, firstQualifier)
INSTANCE_APIS.get(ConnectionSource.DEFAULT).put(name, instanceApi)
def validationApi = getValidationApi(cls, firstQualifier)
VALIDATION_APIS.get(ConnectionSource.DEFAULT).put(name, validationApi)
DATASTORES.get(ConnectionSource.DEFAULT).put(name, this.datastore)
}
for (qualifier in qualifiers) {
def staticApi = getStaticApi(cls, qualifier)
def name = entity.name
STATIC_APIS.get(qualifier).put(name, staticApi)
def instanceApi = getInstanceApi(cls, qualifier)
INSTANCE_APIS.get(qualifier).put(name, instanceApi)
def validationApi = getValidationApi(cls, qualifier)
VALIDATION_APIS.get(qualifier).put(name, validationApi)
DATASTORES.get(qualifier).put(name, this.datastore)
}
}
}
I tried to obtain Grails context to dynamically add domain, but all failed
Upvotes: 0
Views: 27