代码之家  ›  专栏  ›  技术社区  ›  ataylor

域类是否可以配置为在保存时插入新记录而不是更新?

  •  2
  • ataylor  · 技术社区  · 15 年前

    当我更改域对象而不是更新数据库记录时,我希望存档旧记录并创建新记录。我想强迫戈姆自动做这件事。

    例如,如果我有这个域类:

    class User {
        String username
        String email
        Boolean active
    }
    

    然后我想

    user.email = email
    user.save()
    

    要将用户的活动标志设置为假,请保留旧电子邮件的记录。将插入新电子邮件地址为active=true的新记录。

    这是一种常见的模式吗?在域类中这样做容易透明吗?

    2 回复  |  直到 15 年前
        1
  •  2
  •   fabien7474 Jan Tchärmän    15 年前

    您可以使用GORM事件 beforeUpdate 进入用户域类(参见文档 here here )有了如下功能,应该可以工作(而不是测试):

    def beforeUpdate() {
      if (isDirty('email') { //enters only if email was changed. Works only with Grails 1.3.x
      User.withNewSession {
        //Create the new entry
        new User(username:username, email:email).save()
        //Update the old entry with the old email value
        email = getPersistentValue('email')
      }
      }
    }
    
        2
  •  2
  •   Pascal Thivent    15 年前

    我能想到的一个选择是实现 soft delete 然后保持一个新用户。我知道这不是你想要的,但我不知道如何用一次救球来完成。不理想的IMO。

    另一种(可能更好的)方法是 Hibernate Envers 到“版本” User 实体并保留更改的历史记录。我不知道有颗粒的环境的确切状态,但看起来有一个 plugin 为了它。也见 [grails-user] GORM & Envers / Audit History Tables .

    推荐文章