0

比如说,对于一个系统,我有 Student 和 User 对象,如下所示:

User { 
}

Student {
    User user //not nullable
    static belongsTo = [User]
}
Teacher {
    static belongsTo = [user:User]
}

我有很多针对这些模型编写的代码,其中还有很多动态查找器

def u1 = new User().save( flush: true)
new Student( user: u1 ).save( flush: true)
...

def s = Student.findByUser( springSecurityService.currentUser)
//s can be null
def t = Teacher.findByUser( springSecurityService.currentUser)
//t can be null
if( s != null)
    //do something with 's'
if( t != null)
    //do something with 't'
...

这一切都很好。但我想更新我的域模型以添加从用户到学生的级联访问。所以我做了:

User {
  Student student //nullable
}

我会像这样保存一个用户:

new User( student: new Student() ).save( flush: true)

但问题是,当我尝试像上面那样访问“s”时。

如果Student.findByUser可以找到一个这样的学生,那么它就可以工作。
但是如果它应该返回 null,它会给出一个错误。

def s = Student.findByUser( springSecurityService.currentUser)   

将导致:

org.h2.jdbc.JdbcSQLException                                                    

Parameter #2 is not set; SQL statement:

select this_.id as id18_0_, this_.version as version18_0_, from student this_ where this_.id=? limit ? [90012-173]

我知道我可以通过user.student之类的用户对象访问学生对象,但我希望能够保持现有代码不变。

我看过这个帖子,它也有类似的问题,但没有解决grails 电子邮件列表


这是一个错误吗?我能做些什么来绕过它?我没有正确设置我的域模型吗?

谢谢

4

1 回答 1

0

作为替代方案,您可以尝试使用hasOne代替belongsTo.

class User {
    static hasOne = [student:Student, teacher:Teacher]
    static constraints = {
        student unique:true, nullable: true
        teacher unique:true, nullable: true
    }
}

class Student {
    User user
}

class Teacher {
    User user
}

它仍然级联并且似乎可以很好地处理空搜索。

于 2014-08-01T15:55:33.593 回答