由于null id,Grails belongsTo关系因保存而失败

时间:2015-12-25 11:02:41

标签: java hibernate grails

我的GORM关系管理遇到了一些问题。基本上,这个问题范围内有4个域类。 House是一家餐馆,其中有多个Queue,每个Ticket都有多个Customer。门票属于Ticket

主要问题是,当我使用CustomerQueue实例创建customer_ID时,hibernate会抱怨nullTicketclass Ticket implements Comparable<Ticket> { int number; boolean isValid; static belongsTo = [customer: Customer, queue: Queue] public Ticket(Customer customer, Queue queue,int number){ println "Create ticket, customer: ${customer}, queue:${queue}, number:${number}"; customer = customer; queue = queue; number = number; isValid = true; } } 域类看起来像这样:

Ticket

错误发生在一个控制器类中,我在其中创建//c and q are Customer and Queue instances that have passed null check Ticket t = new Ticket(c, q, 10);//In the constructor I see the Customer and Queue instances are not null indeed t.save(flush: true); if (t.hasErrors()) { log.error t.errors; return; } 并保存它。

Customer_ID

错误是空的Ticket,我不太明白。我已经通过客户并排队到Message: NULL not allowed for column "CUSTOMER_ID"; SQL statement: insert into ticket (id, version, customer_id, is_valid, number, queue_id) values (null, ?, ?, ?, ?, ?) [23502-176]构造函数,但为什么Grails在保存时似乎与id不匹配?我已经验证客户ID已成功生成。请指出我在GORM设置中犯的错误。

.ready()

1 个答案:

答案 0 :(得分:1)

这实际上是参数同名的阴影问题。领域。只需像这样更改构造函数:

class Ticket implements Comparable<Ticket> {
    int number;
    boolean isValid;

    static belongsTo = [customer: Customer, queue: Queue]

    public Ticket(Customer customer, Queue queue, int number) {
        println "Create ticket, customer: ${customer}, queue:${queue}, number:${number}";
        this.customer = customer;
        this.queue = queue;
        this.number = number;
        this.isValid = true;
    }
}

您必须在构造函数中使用this关键字,因为域字段customerqueue以及其他内容由构造函数参数提供。

https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

由于customer = customer你将构造函数参数的值赋给它自己,你应该做this.customer = customer(对所有其他人来说都是一样的)