我在更新域类时遇到问题。我正在使用 Grails 3.0.9 和 MongoDB(对于 Gorm 5.0.0.RC1)
在我的 build.gradle 中:
compile "org.grails.plugins:mongodb:5.0.0.RC1"
compile "org.mongodb:mongodb-driver:3.0.2"
compile "org.grails:grails-datastore-gorm-mongodb:5.0.0.RC1"
runtime 'org.springframework.data:spring-data-mongodb:1.8.1.RELEASE'
compile("org.grails:gorm-mongodb-spring-boot:5.0.0.RC1")
考试:
@Integration
class CompanyControllerIntegrationSpec extends Specification{
def grailsApplication
Company company
RestBuilder rest
def setupData() {
company = Company.buildWithoutSave().save(flush: true, failOnError: true)
}
def setup(){
rest = new RestBuilder()
}
def "test update a company" (){
def company2
given:
setupData()
def id = company.id
when:
RestResponse response = rest.put("http://localhost:${grailsApplication.config.server.port}/${company.companyKey}/company") {
json {
name = "newName"
description = "new Description"
}
}
company2 = Company.findById(id)
then:
response.status == 200
response.json.name == "newName"
company2.name == "newName"
company2.description == "new Description"
}
def cleanup() {
Company.collection.remove(new BasicDBObject())
}
}}
控制器:
class CompanyController extends ExceptionController{
static allowedMethods = ['update':'PUT','show':'GET',
'updateNew':'PUT','showNew':'GET']
CompanyService companyService
def update(String companyKey){
def object = request.JSON?request.JSON:params
Company companyOut = companyService.update(object, companyKey)
render text:companyOut as JSON, status:HttpStatus.OK
}
}
服务:
class CompanyService {
def securityService
def grailsApplication
public Company update(object, String companyKey) throws ForbiddenException, InvalidRequestException, NotFoundException{
Company company = findByKey(companyKey)
if (object.name!=null)
company.name = object.name
if (object.description!=null)
company.description = object.description
if (object.enterprise!=null)
company.enterprise = object.enterprise
if (object.genKey!=null)
company.companyKey = UUID.randomUUID().toString()
if (!company.save(flush:true)){
println company.errors
throw new InvalidRequestException("Some parameters are missing or are invalid: "+company.errors.fieldErrors.field)
}
return company
}
public Company findByKey(String companyKey) throws NotFoundException, ForbiddenException {
if (!companyKey){
throw new ForbiddenException("The company key has not been given")
}
Company company = Company.findByCompanyKey(companyKey)
if (!company){
throw new NotFoundException("No company exists for the given key")
}
return company
}
}
测试的结果是:
- response.status 是 200
- response.json.name 是“newName”
- company.name 是旧名称(“company 1”)
如果我不进行清理,数据库仍然具有旧值。我遵循了保存方法,也在 Mongo gorm 类中,我发现一个问题是字段没有被标记为脏,但不知道为什么。对于与此类似的其他域类,更新完成没有问题,并且属性被标记为脏。