Grails:防止更新外键的内容

Grails: Prevent Contents of the foreign key getting Updated

我有如下所示的域 类

class College implements Serializable
{
    String name
    String description
}

class Student implements Serializable
{
    String name
    College college 
}

我在 StudentController 中有 UpdateStudent 操作,它接受 Student 对象并更新 MySQL 数据库中的数据,我面临的问题是外键 "College" 也在更新"Student",这是不可取的,我只想更新 Student 对象而忽略外键。

作为解决方法,我正在使用

student.college.refresh()

在从数据库中获取大学对象并忽略学生中的大学对象的操作中,但是由于代码库很大,因此很难在所有地方对大学对象调用 refresh()。我该如何解决这个问题?

我正在使用 Grails 3。

示例学生对象

{
    "id":1,
    "name":"Arjun",
    "college":{
     "id":1,
     "name":"XYZ College",
     "description": "Test description"
    }
}

这里我更新Student对象的时候不应该更新college对象的内容。

我不清楚你的问题,但你可以尝试以下操作:

在保存您的 Student 对象时添加 deepValidate:false

student.save(deepValidate:false)

或尝试关注

您可以将约束添加到 Student 域 class:

static constraints = {
        college blank: true, nullable: true
    }

默认情况下,所有域 class 属性都不可为空(即它们具有隐式 nullable: false 约束)。

希望对您有所帮助

我已经在域中使用瞬变解决了这个问题,现在域看起来像

 class College implements Serializable
{
    String name
    String description
    boolean update

    transients = ['update']

    def beforeUpdate()
    {
       if(!this.update)
          return false
    }}

现在如果我想主动更新对象,我会在 college.save()

之前调用 college.update = true