我使用运行时数据源插件来拥有第二个数据源,并在运行时通过创建一个名为TableDefinition的域来创建动态表,以将表信息保留在主数据源中,但是在保存该域实例之前,我想在第二个数据源上创建实际的表,但是它在NullPointerException中失败,而实际表是在第二数据库中创建的,但是域实例未持久保存。
第二次数据源服务执行
class DataConnectionService {
def runtimeDataSource
static transactional = true
def execute( String query, String dsName )
{
try
{
Sql sql = runtimeDataSource.getSql( dsName )
return sql.execute( query )
}
catch ( Exception e )
{
log.error( "Error in executing query $query [$e.message]", e )
return null
}
finally
{
sql.close()
}
}
}
域的beforeInsert方法
def beforeInsert()
{
try {
String q = "Create Table test ...."
dataConnectionService.execute( q, dsName )
}
catch( e )
{
log.error "Creating table in 2nd db failed [$e.message]"
return false
}
}
异常堆栈类似于:
->> 163 | removeBatchLoadableEntityKey in org.hibernate.engine.spi.BatchFetchQueue
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 388 | addEntity in org.hibernate.engine.internal.StatefulPersistenceContext
| 461 | addEntity . . . . . . . . . . . in ''
| 143 | makeEntityManaged in org.hibernate.action.internal.AbstractEntityInsertAction
| 203 | addResolvedEntityInsertAction . in org.hibernate.engine.spi.ActionQueue
| 181 | addInsertAction in ''
| 216 | addAction . . . . . . . . . . . in ''
| 324 | addInsertAction in org.hibernate.event.internal.AbstractSaveEventListener
| 288 | performSaveOrReplicate . . . . in ''
| 194 | performSave in ''
| 125 | saveWithGeneratedId . . . . . . in ''
| 209 | saveWithGeneratedOrRequestedId in org.hibernate.event.internal.DefaultSaveOrUpdateEventListener
| 194 | entityIsTransient . . . . . . . in ''
| 114 | performSaveOrUpdate in ''
| 90 | onSaveOrUpdate . . . . . . . . in ''
| 684 | fireSaveOrUpdate in org.hibernate.internal.SessionImpl
| 676 | saveOrUpdate . . . . . . . . . in ''
| 671 | saveOrUpdate in ''
| 58 | doInHibernate . . . . . . . . . in org.codehaus.groovy.grails.orm.hibernate.metaclass.SavePersistentMethod$1
| 188 | doExecute in org.codehaus.groovy.grails.orm.hibernate.GrailsHibernateTemplate
| 132 | execute . . . . . . . . . . . . in ''
| 56 | performSave in org.codehaus.groovy.grails.orm.hibernate.metaclass.SavePersistentMethod
| 215 | doInvokeInternal . . . . . . . in org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractSavePersistentMethod
| 69 | invoke in org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractDynamicPersistentMethod
最佳答案
在对事务和查询使用不同的选项之后,以下组合允许成功执行查询并保存域实例:
static transactional = false
sql.executeUpdate( query )
如果有人可以提供某种有关此行为的原因或任何更好的优化替代方案,那将是很好的。
关于grails - NPE的域的beforeInsert方法中的第二个数据存储中创建表失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30267049/