如何在 Grails 中进行保存或更新?

发布于 2024-11-03 05:42:39 字数 2292 浏览 5 评论 0原文

如果记录不存在,则应插入。 如果记录存在,Grails 应该进行更新。

new MyEntity(attr1:'val1', attr2:'val2').saveOrUpdate()????

编辑 我已根据您的建议修改了我的代码:

List<NutDto> res = np.parseNutData(file.inputStream);
for(NutDto cellValue : res){
    def nutInstance = NutData.get(cellValue.getIdd())       
    System.out.println("nutInstance = " + nutInstance);         
    if(nutInstance){
        System.out.println("Exists : " + nutInstance);
        nutInstance.foo=cellValue.getFoo()
        nutInstance.bar=cellValue.getBar()              
    }
    else{
        System.out.println("Not Exists")
        nutInstance =   new NutData(idd:cellValue.getIdd(),
                foo:cellValue.getFoo(),
                bar:cellValue.getBar())
    }

    def saveres = nutInstance.save(failOnError: true);
    println("saveres = " + saveres);
    nutInstance.errors.each { println it }
}

仍然没有更新。它的抛出错误。

Field error in object 'sps.NutData' on field 'idd': rejected value [123456-1234]; codes [sps.NutData.idd.unique.error.sps.NutData.idd,sps.NutData.idd.unique.error.idd,sps.NutData.idd.unique.error.java.lang.String,sps.NutData.idd.unique.error,nutData.idd.unique.error.sps.NutData.idd,nutData.idd.unique.error.idd,nutData.idd.unique.error.java.lang.String,nutData.idd.unique.error,sps.NutData.idd.unique.sps.NutData.idd,sps.NutData.idd.unique.idd,sps.NutData.idd.unique.java.lang.String,sps.NutData.idd.unique,nutData.idd.unique.sps.NutData.idd,nutData.idd.unique.idd,nutData.idd.unique.java.lang.String,nutData.idd.unique,unique.sps.NutData.idd,unique.idd,unique.java.lang.String,unique]; arguments [idd,class sps.NutData,123456-1234]; default message [Property [{0}] of class [{1}] with value [{2}] must be unique]

这些值没有得到更新。

编辑2

package sps    
class NutData {

    String idd
    String foo
    String bar


    static constraints = {
        idd(blank:false, unique:true)
    }

    static mapping = {
        table 'M_NUT_DATA'
        version false
        id generator: 'assigned', name: "idd", type: 'string'
        foo column:'FOO_COL'
        bar column:'BAR_COL'        
    }

    String toString(){
        return idd + '_' + foo
    }
}

If the record doesnt exist, it should insert.
And if the record exists, Grails should do an update.

new MyEntity(attr1:'val1', attr2:'val2').saveOrUpdate()????

EDIT
I have modified my code as per your suggestions:

List<NutDto> res = np.parseNutData(file.inputStream);
for(NutDto cellValue : res){
    def nutInstance = NutData.get(cellValue.getIdd())       
    System.out.println("nutInstance = " + nutInstance);         
    if(nutInstance){
        System.out.println("Exists : " + nutInstance);
        nutInstance.foo=cellValue.getFoo()
        nutInstance.bar=cellValue.getBar()              
    }
    else{
        System.out.println("Not Exists")
        nutInstance =   new NutData(idd:cellValue.getIdd(),
                foo:cellValue.getFoo(),
                bar:cellValue.getBar())
    }

    def saveres = nutInstance.save(failOnError: true);
    println("saveres = " + saveres);
    nutInstance.errors.each { println it }
}

Still its not updating. Its throwing errors.

Field error in object 'sps.NutData' on field 'idd': rejected value [123456-1234]; codes [sps.NutData.idd.unique.error.sps.NutData.idd,sps.NutData.idd.unique.error.idd,sps.NutData.idd.unique.error.java.lang.String,sps.NutData.idd.unique.error,nutData.idd.unique.error.sps.NutData.idd,nutData.idd.unique.error.idd,nutData.idd.unique.error.java.lang.String,nutData.idd.unique.error,sps.NutData.idd.unique.sps.NutData.idd,sps.NutData.idd.unique.idd,sps.NutData.idd.unique.java.lang.String,sps.NutData.idd.unique,nutData.idd.unique.sps.NutData.idd,nutData.idd.unique.idd,nutData.idd.unique.java.lang.String,nutData.idd.unique,unique.sps.NutData.idd,unique.idd,unique.java.lang.String,unique]; arguments [idd,class sps.NutData,123456-1234]; default message [Property [{0}] of class [{1}] with value [{2}] must be unique]

The values are not getting updated.

EDIT 2

package sps    
class NutData {

    String idd
    String foo
    String bar


    static constraints = {
        idd(blank:false, unique:true)
    }

    static mapping = {
        table 'M_NUT_DATA'
        version false
        id generator: 'assigned', name: "idd", type: 'string'
        foo column:'FOO_COL'
        bar column:'BAR_COL'        
    }

    String toString(){
        return idd + '_' + foo
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

夜深人未静 2024-11-10 05:42:39

动态查找器正是用于此目的。

使用 findOrSaveBy* 您的第一个示例代码将编写如下:

def entity = MyEntity.findOrSaveByAttr1AndAttr2( val1, val2 )

文档: http://grails.org/doc/latest/ref/Domain%20Classes/findOrSaveBy.html

Dynamic finders are precisely available for this purpose.

Using findOrSaveBy* your first sample code would be written as such:

def entity = MyEntity.findOrSaveByAttr1AndAttr2( val1, val2 )

Documentation : http://grails.org/doc/latest/ref/Domain%20Classes/findOrSaveBy.html

星光不落少年眉 2024-11-10 05:42:39

.save() 应该完成这一切,但这取决于您创建对象的方式。

如果您使用 new MyEntity(..) grails 将创建记录,如果您从数据库获取对象,则保存将进行更新。

A .save() should do this all, but it depends on the way you created the object.

if you use new MyEntity(..) grails will create the record, if you get the object from database, the save will do an update.

意犹 2024-11-10 05:42:39

您可以使用以下代码(将 Widget 替换为您的类/实体):

def widgetInstance = Widget.findByName('firstWidget') ?: new Widget(name: 'firstWidget').save(failOnError: true)

保存函数的参数“failOnError: true”将确保代码在出现错误时失败。

You could use the following code (replace Widget with your class/entity):

def widgetInstance = Widget.findByName('firstWidget') ?: new Widget(name: 'firstWidget').save(failOnError: true)

The argument to the save functions "failOnError: true" will ensure that the code will fail in case there is an error.

拥有 2024-11-10 05:42:39

正如 elCapitano 所说,这里的问题很大程度上取决于获取对象的方式。

如果从数据库获取对象,然后修改它,只需对该对象调用 save() 即可。

如果您创建一个新对象(如您的示例):现在这取决于您如何知道“数据库中已存在相同的对象”。您必须执行查询以确定对象是否已存在,然后相应地执行更新或创建。这没有捷径。

但更常见的是,问题并不那么复杂,因为通常只有在已经加载对象(例如加载到表单)以供用户编辑时才更新对象。否则,您知道需要创建该对象。

您可以使用 grails 脚手架 函数来查看 Grails 的典型模型是如何做的CRUD(创建-更新-删除)。

Like elCapitano says, the problem here depends a lot on the way you obtain the object.

If you get the object from database, then modify it, you just need to call save() on the object.

If you create a new object (like your example): now it depends on how you know "the same object already exists in database". You must perform query to determine if the object already exists, then perform update or create accordingly. There's no shortcut for that.

But more often, the problem isn't that complicated, since usually you only update object if already loading it (to a form, for example) for users to edit. Otherwise, you know you need to create the object.

You can use grails scaffolding function to see the typical model how Grails do CRUD(create-update-delete).

顾冷 2024-11-10 05:42:39

为了更新记录,我们应该清楚 -- 如果我的域类有 a、b、c 和 d 字段。然后,在尝试保存 a 和 b 是否相同时更新记录,否则插入新记录。

因此,首先在您的域类中识别这些字段。

然后我们需要域类上的 saveOrUpdate 方法,该方法执行如下操作:

//This method is present in domain class
saveOrUpdate()
{
   //listOfFields is a list of fields that are identifiers or the once that decide whether to update or insert.
   def existingObject = DomainClass.findWhere([this.properties.subMap(listOfFields)])

   if(existingObject)
   {
      // Hey!!! This object already exists in DB. Let us update it .... 
      // Update the existingObject and save the same
   }
else{
    // No object already exists in the DB so, let us create a new one and save it.
   } 
}

如果您想完成相同的工作实现,请参阅我的博客:

http://www.intelligrape.com/blog/2011/03/15/implementing-saveorupdate-for-域类/

希望这有帮助。

In order to update the record we should be clear with -- If my domain class has a,b,c and d fields. Then, while trying to save if a and b are same than update the record other wise insert a new record.

So, First of all identify these fields in your domain class.

Then we need a saveOrUpdate method on the domain class which does something like following:

//This method is present in domain class
saveOrUpdate()
{
   //listOfFields is a list of fields that are identifiers or the once that decide whether to update or insert.
   def existingObject = DomainClass.findWhere([this.properties.subMap(listOfFields)])

   if(existingObject)
   {
      // Hey!!! This object already exists in DB. Let us update it .... 
      // Update the existingObject and save the same
   }
else{
    // No object already exists in the DB so, let us create a new one and save it.
   } 
}

In case you would like to go through a working implementation of the same please refer to my blog :

http://www.intelligrape.com/blog/2011/03/15/implementing-saveorupdate-for-domain-classes/

Hope this helps.

浅暮の光 2024-11-10 05:42:39

<块引用>

“.save()”应该完成这一切,但这取决于您创建对象的方式。

如果你使用 'new MyEntitiy(..)' grails 会创建记录,如果你从 >> 获取对象数据库,保存将进行更新。

正是说到点子上了。首先检索对象,检查更改的内容然后将其保存回来。
使用 new 会在保存期间在数据库中创建另一个条目,“仅仅因为”它是一个 new 对象。

def gottenFromDB = TheObject.get( params.id ) ; //for example
def updatesObject = new MakeNewObjectFromJSON( request ) ; // this one contains the updates

// either check property  by property or just update all properties 
// whatever is more efficiente or if you don't care.

gottenFromDB.prop1 = updatesObject.prop1
gottenFromDB.prop2 = updatesObject.prop2
gottenFromDB.propN   = updatesObject.propN

gottenFromDB.save() ; // this will perform "update"

a '.save()' should do this all, but it depends on the way you created the object.

if you use 'new MyEntitiy(..)' grails will create the record, if you get the object from >> database, the save will do an update.

Exactly to the point. First retrieve the object, check what's changed then save it back.
Using new would create another entry in the DB during the save "just because" it's a new object.

def gottenFromDB = TheObject.get( params.id ) ; //for example
def updatesObject = new MakeNewObjectFromJSON( request ) ; // this one contains the updates

// either check property  by property or just update all properties 
// whatever is more efficiente or if you don't care.

gottenFromDB.prop1 = updatesObject.prop1
gottenFromDB.prop2 = updatesObject.prop2
gottenFromDB.propN   = updatesObject.propN

gottenFromDB.save() ; // this will perform "update"
原来是傀儡 2024-11-10 05:42:39

findOrSaveBy... 不会更新现有数据。
因此,我为名为 Person 的域编写了自己的代码。

Boolean saveOrUpdate(Integer id, String name, Status status, Date startDate) {

    Person person = Person.findById(id)

    //If the person is new, create a new instance and assign ID
    if(!person) {
        person = new Person()
        person.setId(id.toLong()) 
       /** I set the ID here because I am using Postgres and I want to assign the ID manually
       `static mapping = {
           id generator: 'assigned'
        }`
       */
    }

    person.name = name
    person.status = status
    person.startDate = startDate
    person.save(flush: true, failOnError: true)

    if (person?.hasErrors()) {
        log.error("Person ${id} is not saved. Domain Errors: ${person?.errors}")
    }
}

findOrSaveBy... does not update existing data.
Hence, I wrote my own code for a domain called Person.

Boolean saveOrUpdate(Integer id, String name, Status status, Date startDate) {

    Person person = Person.findById(id)

    //If the person is new, create a new instance and assign ID
    if(!person) {
        person = new Person()
        person.setId(id.toLong()) 
       /** I set the ID here because I am using Postgres and I want to assign the ID manually
       `static mapping = {
           id generator: 'assigned'
        }`
       */
    }

    person.name = name
    person.status = status
    person.startDate = startDate
    person.save(flush: true, failOnError: true)

    if (person?.hasErrors()) {
        log.error("Person ${id} is not saved. Domain Errors: ${person?.errors}")
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文