我有一个如下所示的命令对象...
@Validateable
class ACommand implements Serializable
{
ADomainObject bundleDef
}
我使用表单来填写命令,然后使用类似于此的 Controller
def save(ACommand command)
我还将以下内容添加到我的 Config.groovy
grails.gorm.autoFlush = false
问题是即使我不刷新(甚至不调用.save())它仍然会在返回时保存到数据库中。有没有人经历过这个?有办法解决吗?
更新
还尝试了以下
def save(ACommand command)
{
try{
service.saveADomainObject(command.adomain) //save called in here if no error
}
catch(Exception e3){
log.error(e3);
command.adomain.discard()
}
// renders ...
}
这也不起作用,即使调用了丢弃(我设置了一个断点)它仍然保存。
更新 2
我将服务更改为如下所示
adomain.discard()
throw new InvalidObjectException("Blah Blah Blah")
似乎在抛出错误后直接保存到数据库中。我还确认我的服务是交易性的。
更新 3
添加我的服务类以供引用
@Transactional(readOnly = true)
def saveADomainObject(def adomain, def test) throws InvalidParameterException, InvalidObjectException, Exception{
if (!test)
{
throw new InvalidParameterException("*")
}
else
{
if (adomain?.id)
{
if (!isValidBundleName(adomain, test))
{
//TODO: Make default.cannot.save.message
throw new InvalidObjectException("*")
}
errors = updateDomain(adomain)
}
else
{
errors = createNewdomain(adomain)
}
if (errors)
{
throw new Exception(errors)
}
}
}
protected def updateDomain(def adomain)
{
adomain.updatedBy = user
String errors=null;
if (adomain.getErrors().allErrors.size() > 0)
{
errors = adomain.getErrors().allErrors.join("\n")
}
return errors
}
private def createNewdomain(def adomain)
{
adomain.createdBy = user
String errors = null
if (adomain.getErrors().allErrors.size() > 0)
{
errors = adomain.getErrors().allErrors.join("\n")
}
return errors
}
最佳答案
如果 ADomainObject bundleDef
绑定(bind)到已经持久化的对象(即,如果绑定(bind)此对象从数据库加载记录),那么当 Hibernate session 关闭时,对该对象的更改将自动保存到数据库中。
假设如果约束无效,您不想保存对象,请执行以下操作:
def save(ACommand command) {
if (!command.adomain.save()) {
log.error "Failed to save domain due to errors $command.adomin.errors"
// other error handling - maybe show a form that allows the user to correct the errors
} else {
// object saved successfully, redirect to homepage, throw a party, or whatever
}
}
关于hibernate - 命令对象中的 Grails 域对象始终保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23229761/