java – 如何确保对多列(mm_book_id和mm_author_id)应用唯一约束?

我想知道是否有人知道如何确保在联接表mm_author_books中,如何确保列(mm_book_id和mm_author_id)是唯一的?
例如,我不希望表包含book_id和author_id的重复记录,如1,1和1,1.那怎么做……

class Book {
    String title 
    static belongsTo = Author 
    static hasMany = [authors:Author]
    static mapping = { 
        authors joinTable:[name:"mm_author_books", key:'mm_book_id' ] 
    }
}

class Author { 
    String name
    static hasMany = [books:Book]
    static mapping = { 
        books joinTable:[name:"mm_author_books", key:'mm_author_id'] 
    }
}

我在“mm_author_books”域中尝试了这个:

class mm_author_books {

 String book_agency_name    
 static constraints = {
    book_agency_name(unique:['mm_author_id','mm_book_id'])
    }
static belongsTo = [authors:Author, books:Book]

}

但得到以下错误:

Caused by:
org.codehaus.groovy.grails.validation.exceptions.ConstraintException:
Exception thrown applying constraint
[unique] to class [class
content_hub_admin.mm_author_books] for
value [[mm_author_id, mm_book_id]]:
Scope for constraint [unique] of
property [name] of class [class
content_hub_admin.mm_author_books]
must be a valid property name of same
class at
content_hub_admin.mm_author_books$_clinit_closure1.doCall(mm_author_books.groovy:6)
at
content_hub_admin.mm_author_books$_clinit_closure1.doCall(mm_author_books.groovy)
… 28 more

谢谢&问候

rsheyeah

解决方法:

类mm_author_books(更好的名称是AuthorBookRelationship)没有属性mm_author_id和mm_book_id.试试这个:

class AuthorBookRelationship {

    String bookAgencyName

    static constraints = {
        bookAgencyName(unique:['author','book'])
    }

    static belongsTo = [author:Author, book:Book] //only one author and one book

    }
}
上一篇:mysql – Grails – 启动内存/内存使用/域对象


下一篇:Grails – 使用Java域类使用GORM创建grails域类