【发布时间】:2016-09-08 17:57:09
【问题描述】:
目标
在运行集成测试时,我想使用 GORM 使用预设数据填充数据库。
问题
对于某些域,本机 SQL 查询无法查看 GORM 插入的数据,反之亦然(GORM 查询无法查看本机 SQL 插入的数据)。在一次运行中,一个域会出现此问题,而另一个则不会。
说明
请查看本文底部附近的控制台输出以获得清晰的描述。我认为可以在输出中看到解决方案的线索。
项目:Grails 2.4.2 数据来源:
test {
cehCode = "PR"
schemaName = "AF"
parallelSchemaName = "AF"
dataSource {
dbCreate = "create-drop"
url = "jdbc:h2:mem:testDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS AF"
driverClassName = "org.h2.Driver"
properties {
initialSize = 2
minIdle = 1
maxIdle = 2
maxActive = 2
maxWait = 2000
maxAge = 60000
minEvictableIdleTimeMillis=30000
timeBetweenEvictionRunsMillis=30000
abandonWhenPercentageFull = 50
numTestsPerEvictionRun=3
testOnBorrow=true
testWhileIdle=true
testOnReturn=true
validationQuery="SELECT 1"
validationInterval=500
//defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_UNCOMMITTED
}
}
}
集成测试:
void "Test CUST filter"() {
when: 'Build test data'
then:
assert testQueryService.testInsert() == "Done with inserts"
assert testQueryService.testQuery() == "Done with queries"
}
服务:
package com.lrs.accrual.common
import com.lrs.contract.TFastCodes
import grails.transaction.Transactional
import groovy.sql.Sql
import com.lrs.accrual.IntermodalRatingAuth
@Transactional
class TestQueryService {
def sessionFactory
def testInsert() {
println "----------------------START EXECUTING INSERTS ON TABLES------------------------------"
println "********* START NEW TABLE/DOMAIN TFAST_CODES/TFastCodes *********"
def nativeInsert = """INSERT INTO AF.TFAST_CODES (APPL_ELE,APPL_CD_VAL,APPL_CD_DESC,CAS_OWNER,ACS_TYPE_CD)
VALUES ('NATIVE SQL2','1','ORPT-TEST PR','ZZZZ','BU')"""
def sql = new Sql(sessionFactory.getCurrentSession().connection())
sql.executeInsert(nativeInsert)
sql.commit()
TFastCodes codes = new TFastCodes(applicationElement: 'GORM new 3', casOwner: 'ZZZZ', applicationCodeDescription: 'JUNK2', applicationCodeValue: '1', accessTypeCode: 'BU', newColumn2: 'Val')
println "Valid TFastCodes domain? " + codes.validate()
codes.save(flush: true)
println "********* END NEW TABLE/DOMAIN *********"
println "********* START OLD TABLE/DOMAIN TIMDL_RT_AUTH/IntermodalRatingAuth *********"
def nativeInsert2 = """INSERT INTO AF.TIMDL_RT_AUTH (AGREEMENT_NUMB,MRKT_RATE_KEY,WB_RT_AUTH_REF)
VALUES ('NATIVE',1,'2016-01-01-01.01.01.000000')"""
def sql2 = new Sql(sessionFactory.getCurrentSession().connection())
sql2.executeInsert(nativeInsert2)
sql2.commit()
IntermodalRatingAuth auth= new IntermodalRatingAuth(agreementNumber:"GORM", marketingRateKey:1, waybillRateAuthRef: "other string")
println "Valid IntermodalRatingAuth domain? " + auth.validate()
auth.save(flush: true)
println "********* END OLD TABLE/DOMAIN *********"
println "----------------------END EXECUTING INSERTS ON TABLES------------------------------"
return "Done with inserts"
}
def testQuery() {
println "----------------------START EXECUTING QUERIES ON TABLES------------------------------"
println "********* START QUERIES AGAINST NEW TABLE/DOMAIN TFAST_CODES/TFastCodes *********"
def codes = TFastCodes.list()
codes?.eachWithIndex { val, i -> println "Gorm TFastCodes result $i: " + val.properties }
println "Native TFAST_CODES query result: " + sessionFactory.getCurrentSession()?.createSQLQuery("SELECT * FROM AF.TFAST_CODES").list()
println "********* END QUERIES AGAINST NEW TABLE/DOMAIN TFAST_CODES/TFastCodes *********"
println "********* START QUERIES AGAINST OLD TABLE/DOMAIN TIMDL_RT_AUTH/IntermodalRatingAuth *********"
def auths = IntermodalRatingAuth.list()
auths?.eachWithIndex { val, i -> println "Gorm IntermodalRatingAuth result $i: " + val.properties }
println "Native TIMDL_RT_AUTH query result: " + sessionFactory.getCurrentSession()?.createSQLQuery("SELECT * FROM AF.TIMDL_RT_AUTH").list()
println "********* END QUERIES AGAINST OLD TABLE/DOMAIN TIMDL_RT_AUTH/IntermodalRatingAuth *********"
println "----------------------END EXECUTING QUERIES ON TABLES------------------------------"
return "Done with queries"
}
}
从头开始创建的域(有效):
class TFastCodes implements Serializable {
String applicationElement
String applicationCodeValue
String applicationCodeDescription
String casOwner
String accessTypeCode
static mapping = {
table 'AF.TFAST_CODES'
version false
id composite: ['applicationElement', 'applicationCodeValue']
applicationElement column:'APPL_ELE'
applicationCodeValue column:'APPL_CD_VAL'
applicationCodeDescription column:'APPL_CD_DESC'
casOwner column:'CAS_OWNER'
accessTypeCode column:'ACS_TYPE_CD'
}
static constraints = { applicationElement( blank:false)
applicationCodeValue( blank:false)}
}
现有域(不起作用):
class IntermodalRatingAuth {
String agreementNumber=LRAccrualConstants.STRING_EMPTY
Integer marketingRateKey= LRAccrualConstants.ZERO
String waybillRateAuthRef
static mapping = {
table 'AF.TIMDL_RT_AUTH'
version false
agreementNumber column:'AGREEMENT_NUMB'
marketingRateKey column:'MRKT_RATE_KEY'
waybillRateAuthRef column:'WB_RT_AUTH_REF'
}
// Read-only. No constraints needed.
}
控制台输出:
----------------------START EXECUTING INSERTS ON TABLES------------------------------
********* START NEW TABLE/DOMAIN TFAST_CODES/TFastCodes *********
Valid TFastCodes domain? true
Hibernate: select tfastcodes_.APPL_ELE, tfastcodes_.APPL_CD_VAL, tfastcodes_.ACS_TYPE_CD as ACS_TYPE3_37_, tfastcodes_.APPL_CD_DESC as APPL_CD_4_37_, tfastcodes_.CAS_OWNER as CAS_OWNE5_37_ from AF.TFAST_CODES tfastcodes_ where tfastcodes_.APPL_ELE=? and tfastcodes_.APPL_CD_VAL=?
Hibernate: insert into AF.TFAST_CODES (ACS_TYPE_CD, APPL_CD_DESC, CAS_OWNER, APPL_ELE, APPL_CD_VAL) values (?, ?, ?, ?, ?)
********* END NEW TABLE/DOMAIN *********
********* START OLD TABLE/DOMAIN TIMDL_RT_AUTH/IntermodalRatingAuth *********
Valid IntermodalRatingAuth domain? true
********* END OLD TABLE/DOMAIN *********
----------------------END EXECUTING INSERTS ON TABLES------------------------------
----------------------START EXECUTING QUERIES ON TABLES------------------------------
********* START QUERIES AGAINST NEW TABLE/DOMAIN TFAST_CODES/TFastCodes *********
Hibernate: select this_.APPL_ELE as APPL_ELE1_37_0_, this_.APPL_CD_VAL as APPL_CD_2_37_0_, this_.ACS_TYPE_CD as ACS_TYPE3_37_0_, this_.APPL_CD_DESC as APPL_CD_4_37_0_, this_.CAS_OWNER as CAS_OWNE5_37_0_ from AF.TFAST_CODES this_
Gorm TFastCodes result 0: [applicationCodeDescription:ORPT-TEST PR, applicationCodeValue:1, accessTypeCode:BU, applicationElement:NATIVE SQL2, casOwner:ZZZZ]
Gorm TFastCodes result 1: [applicationCodeValue:1, accessTypeCode:BU, applicationElement:GORM new 3, casOwner:ZZZZ, applicationCodeDescription:JUNK2]
Hibernate: SELECT * FROM AF.TFAST_CODES
Native TFAST_CODES query result: [[NATIVE SQL2, 1, BU, ORPT-TEST PR, ZZZZ], [GORM new 3, 1, BU, JUNK2, ZZZZ]]
********* END QUERIES AGAINST NEW TABLE/DOMAIN TFAST_CODES/TFastCodes *********
********* START QUERIES AGAINST OLD TABLE/DOMAIN TIMDL_RT_AUTH/IntermodalRatingAuth *********
Gorm IntermodalRatingAuth result 0: [marketingRateKey:1, agreementNumber:GORM, waybillRateAuthRef:other string]
Hibernate: SELECT * FROM AF.TIMDL_RT_AUTH
Native TIMDL_RT_AUTH query result: [[1, NATIVE, 1, 2016-01-01-01.01.01.000000]]
********* END QUERIES AGAINST OLD TABLE/DOMAIN TIMDL_RT_AUTH/IntermodalRatingAuth *********
----------------------END EXECUTING QUERIES ON TABLES------------------------------
其他详情
在我的 Grails 项目中,我为测试环境设置了一个内存数据库。我想在每次运行特定的集成测试时都保存一组新的测试数据。
当使用 GORM (domain.save()) 保存数据时,服务中的 GORM 查询能够很好地找到数据,但无法看到本地 SQL 插入插入的数据。另一方面,sessionFactory 原生 SQL 查询无法看到插入的 GORM 数据,但能够看到原生 SQL 插入的数据。
正如您在下面看到的,我执行了 flush:true 并尝试了所有我知道的命令来提交数据运行。我测试过的大多数域都是现有域,它永远不会立即适用于它们。但是,当我从头开始创建新域时(使用 Grails“创建域”命令),它通常可以工作。在我看来,这个问题在 Grails 或 Hibernate 架构中更深层次的地方。下面的代码示例被简化了,但我有一个服务可以并排演示旧域和新域:
- GORM 和本机 SQL 都将两者插入(每个表中有两行)
- GORM 和本机 SQL 都对两者进行查询
- 旧域显示本地查询的本地插入数据和 GORM 查询的 GORM 插入数据
- 新域显示本地查询的结果和 GORM 查询的结果
如果它有效,它适用于 GORM 和本机。如果不起作用,则双方都看不到对方插入的数据。
我采取的调试步骤:
- 下面的数据源比我开始的要大得多。我的第一个非常基本,没有 AF 架构,没有其他属性等。添加所有内容都是为了尝试排除故障。
- 我已尝试删除可序列化的复合 ID,而且我能找到的几乎所有其他东西都使这变得更加复杂。
- 在每次运行之间,我执行 grails clean-all 命令并删除目标目录
- 我在创建使域开始工作的一致方案时遇到问题,但它通常与更改类、移动包、更改域中定义的表名或创建全新域/表的组合有关.
【问题讨论】:
-
您在
sql.executeInsert(nativeInsert)之后尝试使用sql.commit()吗? -
@droggo,感谢您的评论。我按照你说的添加了提交语句,没有看到任何变化。为了更好地说明,我还添加了我之前提到的第二个域,它适用于一个而不是另一个,并改进了日志记录。需要指出两点: 1. 如您所见,TFAST_CODES 仍然成功找到每个查询的两个插入语句,但 TIMDL_RT_AUTH(旧域)仍然只找到一个。 2. Hibernate 日志语句对于这些的插入和查询是不同的。找到根本原因的线索?不确定。
-
一些想法:您可以尝试包装您的插入 in one transaction 以将其保存在这些查询之前。您还可以使用a new session 来查询和获取数据库的状态。
标签: hibernate grails grails-orm h2 sessionfactory